I need to adapt a suspending function that returns
Flow
to a non-suspending function that returns
Flow
. Is this the correct way to do that?
Copy code
suspend fun suspendingFlow(): Flow<String> { ... }
fun nonSuspendingFlow() = flow {
suspendingFlow().collect {
emit(it)
}
}
v
Vsevolod Tolstopyatov [JB]
04/23/2019, 9:48 AM
Not really.
suspendingFlow()
will be invoked on every
collect
and it is probably not expected behaviour
s
sdeleuze
04/23/2019, 9:49 AM
What is your recommandation for that use case?
v
Vsevolod Tolstopyatov [JB]
04/23/2019, 10:15 AM
There are no good options.
Suspend modifier inherently means that function is asynchronous, so it can’t be simply converted to a plain Java method. You should either return something asynchronous and stateful or use e.g.