Zoltan Demant
08/07/2025, 1:53 PMflow.flowOn(Default)
where it makes sense; and life is good. Or so I would think, because further down the chain when I do flow.map { .. }
and perform some heavy transformations on the data.. Ill eventually realize that Im doing those on the main-thread, since the backing scope is based on Dispatchers.Main
. I need the results of the flow collection to be delivered on the main thread, but Id basically like all operations on it to be performed on a background one. I know that I can use withContext, specify another .flowOn, or even run the entire flow operation in a background scope - and then switch to main for the delivery.. but these seem reluctant or weird, and Id be repeating myself a lot. Is there any best practices or advice for situations like this?Natasha Murashkina
08/07/2025, 2:25 PMflow.map { ... }.flowOn(Dispatchers.Default).collect { ... }
? All the upstream will be executed on Dispatchers.Default, not just map
.Natasha Murashkina
08/07/2025, 2:28 PMZoltan Demant
08/07/2025, 2:29 PMZach Klippenstein (he/him) [MOD]
08/08/2025, 3:06 AMwithContext(Default) {
flow
.map {}
.collect {
withContext(Main) {
…
}
}
}
Zoltan Demant
08/08/2025, 3:13 AMwithContext(Main)
like that?Zoltan Demant
08/08/2025, 3:13 AMZoltan Demant
08/08/2025, 3:15 AMflow.flowOn(Default)
moves the upstream flow operations to the Default
dispatcher, which means all emissions happen on Default
before reaching downstream.
In contrast, using withContext(Main)
inside collect
switches context per collected item, incurring context switch overhead for each emission.Zoltan Demant
08/08/2025, 3:16 AMZach Klippenstein (he/him) [MOD]
08/14/2025, 3:33 PMNatasha Murashkina
08/14/2025, 3:40 PMval flow = upstreamFlow.flowOn(Default)
withContext(Main) { flow.collect { ... } }
I personally think that it is every developer's responsibility to think where they want their code to execute, if they're adding an extra operator. I personally wouldn't recommend either option over the plain and simple flow.map{ ... }.flowOn(Default).collect { ... }
. That's the standard syntax, that's exactly the use case it was created for, no need to complicate.