mbonnin
07/16/2019, 2:33 PMval downloadFlow = flow {
var read = 0
while (read < total) {
read += readFromNetwork() // How do I make this run from a background thread ? <http://Dispatcher.IO|Dispatcher.IO> or other ?
emit(read to total)
}
}
downloadFlow.collect {
// this should run from the main thread
displayProgress(it)
}
What would be the idiomatic way to have a long running background operation emit progress that is read from the main thread ? The flow
doc explicitely prohibits changing context in the flow block.streetsofboston
07/16/2019, 2:35 PMreadFromNetwork
repeatedly, you can make readFromNetwork
a suspend
fun and run it on a background thread (e.g. suspend fun readFromNetwork() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
.
For callback, you use channelFlow
or callbackFlow
instead of plain flow
mbonnin
07/16/2019, 2:36 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
works from flow{}
as long as we don't emit
from ?flowOn
that looks promising...