A Common Mistake when working with Kotlin Flows š„¶
This title could be clearer and more informative.Try out Clickbait Shieldfor free (5 uses left this month).
When using Kotlin Flows, the producer (emitter) inherits the dispatcher from its collector by default. This means if you don't explicitly use the `flowOn` operator in your repository, your flow will run on whatever dispatcher the ViewModel or Composable scope uses ā often the main thread. The correct approach is to always call `flowOn(Dispatchers.IO)` in your repository functions to ensure heavy or expensive operations run on the appropriate dispatcher, regardless of which coroutine scope collects the flow. Two approaches are compared: using `flowOn` in the repository (recommended) vs. passing a dispatcher explicitly to the ViewModel scope (less flexible). Room database handles this internally, but custom flows require manual dispatcher management.
Sort: