https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

reik.schatz

09/25/2019, 7:39 AM
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

gildor

09/25/2019, 7:46 AM
Honestly I don’t understand your case, what exactly you want to convert?
r

reik.schatz

09/25/2019, 7:46 AM
ok some code
data class Foo(val users: List<String>)
suspend fun find(): Foo?
g

gildor

09/25/2019, 7:47 AM
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

reik.schatz

09/25/2019, 7:48 AM
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

gildor

09/25/2019, 7:48 AM
so, looks that
first()
is what you need
r

reik.schatz

09/25/2019, 7:50 AM
that returns me the first item? I need all of them, the whole list
g

gildor

09/25/2019, 7:51 AM
Than use flow.toList()
which suspend until this flow is completed
r

reik.schatz

09/25/2019, 7:51 AM
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

gildor

09/25/2019, 7:53 AM
use common parallelization approach for suspend functions (use async + awaitAll) and call toList() on each of them
r

reik.schatz

09/25/2019, 7:54 AM
thanks, will read up on it
g

gildor

09/25/2019, 7:54 AM
or merge flows first and use toList() after that
r

reik.schatz

09/25/2019, 7:54 AM
flow.flatMapMerge
?
g

gildor

09/25/2019, 7:55 AM
yeah, something like:
Copy code
flowOf("user1", "user2").flatMapMerge { client.execute(it) }.toList()
actually this approach is more simple in this case than
async{}
3 Views