我有些事。而且我必须编写一个函数,该函数应尽快返回第一项,随后对该函数的所有后续调用都将返回流的最新值。
val f = flow {
emit(1)
delay(100)
emit(2)
}
suspend fun getLatest() = f.conflate().first() // this should be fixed, something like latest()
suspend fun main() {
println(getLatest())
delay(100)
println(getLatest())
delay(100)
println(getLatest())
delay(100)
println(getLatest())
}
开始时输出应该为1,在某些时候后输出始终为2。上面的代码始终为s,我不明白为什么。
答案 0 :(得分:1)
因为Flow
是冷流。每次您呼叫first()
时,封锁
emit(1)
delay(100)
emit(2)
将再次被呼叫。
将来,SharedFlow
将被添加到库中,请参见pull request,我们可以这样写:
val f = flow {
emit(1)
delay(100)
emit(2)
}
val coroutineScope: CoroutineScope = ...
val shared = f.conflate().shareIn(
coroutineScope,
replay = 1,
started = SharingStarted.WhileSubscribed()
)
suspend fun getLatest() = shared.first() // this should be fixed, something like latest()
suspend fun main() {
println(getLatest())
delay(100)
println(getLatest())
delay(100)
println(getLatest())
delay(100)
println(getLatest())
}