I am new to coroutines. Lets say I have a suspend ...
# coroutines
r
I am new to coroutines. Lets say I have a suspend function that returns a nullable type. The type has a List field, whose values I read from a db using r2dbc, hence they are returned as a
Flow
. How do I map from a
Flow
to a nullable instance that my suspend function returns? In Reactor there are functions to map a
Flux
to a
Mono
..
g
Honestly I don’t understand your case, what exactly you want to convert?
r
ok some code
data class Foo(val users: List<String>)
suspend fun find(): Foo?
g
Flow doesn’t have direct analogue to Mono, because you have suspend functions, so the closest converter of Flow to suspend function is just call
flow.first()
on it to get first value or wrap it to lambda to make it lazy
okay
r
within
find()
I read users from a db using R2DBC. So I end up having this:
val users: Flow<String> = client.execute ...
now I need to map
users
to an instance of
Foo
g
so, looks that
first()
is what you need
r
that returns me the first item? I need all of them, the whole list
g
Than use flow.toList()
which suspend until this flow is completed
r
ok thanks
let’s say I want to create multiple Flows (using client.execute) in parallel. then I want to suspend until all of them are complete ..
g
use common parallelization approach for suspend functions (use async + awaitAll) and call toList() on each of them
r
thanks, will read up on it
g
or merge flows first and use toList() after that
r
flow.flatMapMerge
?
g
yeah, something like:
Copy code
flowOf("user1", "user2").flatMapMerge { client.execute(it) }.toList()
actually this approach is more simple in this case than
async{}