问题描述
下面我都有两个代码,对我来说结果也一样
val namesFlow = flow {
println("Start flow")
(0..10).forEach {
// Emit items with 500 milliseconds delay
delay(500)
println("Emitting $it")
emit(it)
}
}.map { it * it }
fun main() = runBlocking {
namesFlow.collect { println(it) }
namesFlow.collect { println(it) }
println("Finish Flow")
}
和
val namesFlow = channelFlow {
println("Start flow")
(0..10).forEach {
// Emit items with 500 milliseconds delay
delay(500)
println("Emitting $it")
send(it)
}
}.map { it * it }
fun main() = runBlocking {
namesFlow.collect { println(it) }
namesFlow.collect { println(it) }
println("Finish Flow")
}
flow
和channelFlow
有什么区别?
解决方法
channelFlow
的目的是能够从同时运行的协程中检索结果。这是其documentation中的一个示例,该示例通过同时收集当前流和另一个流并将所有数据发送到同一通道来将另一个流合并到当前流中:
fun <T> Flow<T>.merge(other: Flow<T>): Flow<T> = channelFlow {
launch {
collect { send(it) }
}
other.collect { send(it) }
}