sample 方法是用于对数据流进行采样的操作,它会根据指定的时间间隔或者其它条件从数据流中抽取样本。
以下是三个使用 sample 方法的示例:
使用时间间隔进行采样:
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlockingfun simpleFlow(): Flow<Int> = flow {repeat(10) {emit(it)delay(100) // 每100毫秒发射一个数据}
}fun main() = runBlocking {simpleFlow().sample(300) // 每隔300毫秒采样一次.collect { value ->println(value)}
}
根据条件进行采样:
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlockingfun simpleFlow(): Flow<Int> = flow {repeat(10) {emit(it)delay(100) // 每100毫秒发射一个数据}
}fun main() = runBlocking {simpleFlow().sample {// 当元素的值大于5时进行采样if (it > 5) {true} else {false}}.collect { value ->println(value)}
}