``` val downloadFlow = flow { v...
# coroutines
m
Copy code
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
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>) { ... }
. For callback, you use
channelFlow
or
callbackFlow
instead of plain
flow
m
Ah, alright,
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
works from
flow{}
as long as we don't
emit
from ?
👌 1
Yep, looks like it, thanks !
I also just bumped into
flowOn
that looks promising...
👍 1