我有一些东西在流动。我必须尽快编写返回第一项的函数,然后对该函数的所有调用都返回流的最新值。
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,过了一些时候,总是两次输出。上面的代码总是返回的,我不明白为什么。
发布于 2020-08-27 09:36:41
因为Flow是冷流。每次你打电话给first(),阻止
emit(1)
delay(100)
emit(2)会再次被召唤。
将来,SharedFlow将被添加到库中,请参阅拉请求,我们可以这样编写:
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())
}https://stackoverflow.com/questions/63611674
复制相似问题