我怎樣才能讓下面的流量收集器收到“你好”?收集器正在呼叫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")
}
}
uj5u.com熱心網友回復:
您可以嘗試emitAll為您的案例使用功能:
fun myFunction1(): Flow<String> = flow {
/*some code*/
emitAll(myFunction2())
}
fun myFunction2(): Flow<String> = flow {
/*some code*/
emit("hello")
}
emitAllfunction 收集Flow由myFunction2()function創建的所有值并將它們發送到收集器。
并且沒有理由suspend在每個函式之前設定修飾符,flowbuilder 不是suspend。
uj5u.com熱心網友回復:
除非您有非常具體的原因,否則Flow從您的倉庫回傳 a 的函式不應該暫停(因為flow{}構建器沒有暫停)。由于暫停操作正在收集(等待值從中出來)。
從您提供的代碼中,您正在尋找該flatMapLatest功能。檔案在這里
class Repo {
fun function1() =
flow {
val value = doSomething()
emit(value)
}
.flatMapLatest { emittedValue -> function2() }
fun function2() = flow {...}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/409906.html
標籤:
