mar*_*rs8 0 suspend coroutine kotlin kotlin-coroutines kotlin-flow
如何让下面的流量收集器收到“hello”?收集器正在调用,myFunction1()而收集器又调用myFunction2(). 两者都是挂起函数。
目前,当我点击运行并且没有收到流量时,什么也没有发生。我在这里错过了什么吗?
CoroutineScope(IO).launch {
val flowCollector = repo.myFunction1()
.onEach { string ->
Log.d("flow received: ", string)
}
.launchIn(GlobalScope)
}
Run Code Online (Sandbox Code Playgroud)
class Repo {
suspend fun myFunction1(): Flow<String> = flow {
/*some code*/
myFunction2()
}
suspend fun myFunction2(): Flow<String> = flow {
/*some code*/
emit("hello")
}
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用emitAll适合您情况的函数:
fun myFunction1(): Flow<String> = flow {
/*some code*/
emitAll(myFunction2())
}
fun myFunction2(): Flow<String> = flow {
/*some code*/
emit("hello")
}
Run Code Online (Sandbox Code Playgroud)
emitAllFlow函数从函数创建的 中收集所有值myFunction2()并将它们发送到收集器。
并且没有理由suspend在每个函数之前设置修饰符,flowbuilder 则不是suspend。
| 归档时间: |
|
| 查看次数: |
3627 次 |
| 最近记录: |