How can I have the flow collector below receive "hello"? The collector is calling myFunction1()
which in turn calls myFunction2()
. Both are suspend functions.
Currently nothing happens when I hit run and no flow is received. Am I missing something here?
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")
}
}
You can try to use emitAll
function for your case:
fun myFunction1(): Flow<String> = flow {
/*some code*/
emitAll(myFunction2())
}
fun myFunction2(): Flow<String> = flow {
/*some code*/
emit("hello")
}
emitAll
function collects all the values from the Flow
, created by myFunction2()
function and emits them to the collector.
And there is no reason to set a suspend
modifier before each function, flow
builder isn't suspend
.