`viewModelScope` and `lifecycleScope` both run on ...
# android
m
viewModelScope
and
lifecycleScope
both run on the Main Dispatcher. All the official and unofficial examples of these scopes together with a
StateFlow
or
SharedFlow
show this:
.stateIn(viewModelScope, ...) or .sharedIn(viewModelScope, ...)
. But this means that all the calculations (for example when using
combine
) then run on the main thread. Wouldn’t the better default be to always run
SharedFlow
and
StateFlow
in
viewModelScope + Dispatchers.Default
? When collecting the flow, it will run in another coroutine anyway, and UI operations can be done on the Main dispatcher.
f
We want to be on the Main thread to propagate UI state or UI effects. Calculations can (should) be wrapped with
withContext(Dispatcher)
.
a
"calculations" is pretty vague and can include a lot of different kinds of work. For it to be worth the overhead of swapping threads your work needs to be quite heavy. Generally don't do it unless you've measured a specific problem case.
👍 1