流首先等待,然后在后台处理其余的

时间:2020-08-27 08:03:42

标签: kotlin kotlin-coroutines kotlin-coroutines-flow

我有些事。而且我必须编写一个函数,该函数应尽快返回第一项,随后对该函数的所有后续调用都将返回流的最新值。

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,我不明白为什么。

1 个答案:

答案 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())
}