【问题标题】:Emit Flow via another suspend function in Kotlin通过 Kotlin 中的另一个挂起函数发出流
【发布时间】:2022-12-03 16:11:24
【问题描述】:

我怎样才能让下面的流量收集器收到“你好”?收集器正在调用myFunction1(),后者又调用myFunction2()。两者都是暂停功能。

目前,当我点击运行时没有任何反应,也没有收到任何流量。我在这里错过了什么吗?

CoroutineScope(IO).launch {
    val flowCollector = repo.myFunction1()
        .onEach { string ->
            Log.d("flow received: ", string)
        }
        .launchIn(GlobalScope)
}

class Repo {

    suspend fun myFunction1(): Flow<String> = flow {
        /*some code*/
        myFunction2()
    }

    suspend fun myFunction2(): Flow<String> = flow {
        /*some code*/
        emit("hello")
    }
}

【问题讨论】:

    标签: kotlin kotlin-coroutines coroutine kotlin-flow suspend


    【解决方案1】:

    您可以针对您的情况尝试使用emitAll 函数:

    fun myFunction1(): Flow<String> = flow {
        /*some code*/
        emitAll(myFunction2())
    }
    
    fun myFunction2(): Flow<String> = flow {
        /*some code*/
        emit("hello")
    }
    

    emitAll 函数从 Flow 收集所有值,由 myFunction2() 函数创建并将它们发送到收集器。

    并且没有理由在每个函数之前设置一个suspend修饰符,flow构建器不是suspend

    【讨论】:

    • 谢谢,这个答案有效。当我在 myFunction1/2 (retrofit/room) 中运行异步代码时,我有暂停功能。如果您认为我应该有更多的最佳方式来构建 Repo 类,任何建议/文章将不胜感激。
    【解决方案2】:

    除非你有一个非常具体的原因,否则从你的回购中返回 Flow 的函数不应该被暂停(因为 flow{} 构建器没有暂停)。由于挂起操作正在收集(等待值从中出来)。

    从您提供的代码中,您正在寻找 flatMapLatest 函数。 Docs here

    class Repo {
    
      fun function1() = 
        flow {
          val value = doSomething()
          emit(value)
        }
        .flatMapLatest { emittedValue -> function2() }
      fun function2() = flow {...}
    }
    

    【讨论】:

    猜你喜欢
    • 2020-01-27
    • 2021-12-28
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多