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

Dmitry Khasanov

05/12/2020, 5:57 PM
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

streetsofboston

05/12/2020, 6:01 PM
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

Dmitry Khasanov

05/12/2020, 6:08 PM
unfortunately there is no
launch
function inside
flow
builder
s

streetsofboston

05/12/2020, 6:13 PM
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

Dmitry Khasanov

05/12/2020, 6:20 PM
looks like it is exactly what I need! Thanks a lot!
s

streetsofboston

05/12/2020, 6:24 PM
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

Dmitry Khasanov

05/12/2020, 6:38 PM
thank you for explanation, Anton!
5 Views