```suspend fun loadData(id: Long) = flow { fet...
# coroutines
d
Copy code
suspend fun loadData(id: Long) = flow {
    fetchData(id) <-- now this is blocking function, how can I launch it in non blocking mode?
    roomDao.select(id)
        .collect {
            emit(result)
        }
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)

suspend fun fetchData(id) {
    // make http request here and put data into database
}
Hi all. How can I launch
fetchData
function in parallel from
flow {}
?
s
You could do
launch { fetchData(id) }
Is
fetchData
blocking or suspending?
(still, wrapping it in a
launch
would work, but if it is truly blocking, do
launch(<http://Dispatchers.IO|Dispatchers.IO>) { fetchData(id) }
instead)
d
unfortunately there is no
launch
function inside
flow
builder
s
Wrap the whole body of the flow in
coroutineScope
Copy code
suspend fun loadData(id: Long) = flow {
    coroutineScope {
        launch { fetchData(id) }
        roomDao.select(id)
            .collect {
                emit(result)
            }
    }
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
👍 2
d
looks like it is exactly what I need! Thanks a lot!
s
Note that, in order to have
fetchData
to run in parallel with
roomDao.select...
, you must wrap then entire contents of the `flow`’s code inside
coroutineScope
. This is because
coroutineScope
suspends until all its children have finished, which would include the
launch { fetchData(id) }
. Then to keep things in parallel, the
roomDao.select...
need to be one of the `coroutineScope`’s children as well.
👍 1
d
thank you for explanation, Anton!