val 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.
s
streetsofboston
07/16/2019, 2:35 PM
For polling, as you do here, by calling
readFromNetwork
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>) { ... }