【问题标题】:Flow wait for first, then process the rest in background流程先等待,然后在后台处理其余部分
【发布时间】:2020-08-27 08:03:42
【问题描述】:

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

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

【问题讨论】:

    标签: kotlin kotlin-coroutines


    【解决方案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())
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多