通过 Kotlin 中的另一个挂起函数发出流



如何让下面的流收集器收到"hello"?收集器正在调用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")
}
}

您可以尝试使用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

除非你有非常具体的原因,否则从存储库返回Flow的函数不应该挂起(因为flow{}生成器没有挂起)。由于挂起操作正在收集(等待值从中出来)。

从您提供的代码中,您正在寻找flatMapLatest函数。文档在这里

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

最新更新