Dmitry Khasanov
05/12/2020, 5:57 PMsuspend 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 {}
?streetsofboston
05/12/2020, 6:01 PMlaunch { fetchData(id) }
fetchData
blocking or suspending?launch
would work, but if it is truly blocking, do launch(<http://Dispatchers.IO|Dispatchers.IO>) { fetchData(id) }
instead)Dmitry Khasanov
05/12/2020, 6:08 PMlaunch
function inside flow
builderstreetsofboston
05/12/2020, 6:13 PMcoroutineScope
suspend fun loadData(id: Long) = flow {
coroutineScope {
launch { fetchData(id) }
roomDao.select(id)
.collect {
emit(result)
}
}
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
Dmitry Khasanov
05/12/2020, 6:20 PMstreetsofboston
05/12/2020, 6:24 PMfetchData
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.Dmitry Khasanov
05/12/2020, 6:38 PM