Juan Rada
10/26/2023, 9:37 AMsuspend fun getFlow() = withContext(<http://Dispachers.IO|Dispachers.IO>) {
flow { ... }
}
and
fun getFlow() = flow { ... }.flowOn(<http://Dispachers.IO|Dispachers.IO>)
Joffrey
10/26/2023, 9:38 AMJoffrey
10/26/2023, 9:40 AMwithContext
will only affect the creation of the flow (which is very quick because it doesn't execute the body of the flow
builder). It will suspend the caller and potentially do a context switch just for an instant, just the time it takes to instantiate a flow and return it. Only the flow instantiation and the return will be executed in the IO dispatcher.Joffrey
10/26/2023, 9:41 AMJuan Rada
10/26/2023, 9:46 AMsuspend fun getFlow() = flow {
withContext(Dispatchers.IO) { }
}
Mikhail
10/26/2023, 10:09 AMflowOn
affects not only flow {}
block but also any map
, transform
and similar functions in chain before flowOn
call. In your example behavior will be the same, but if you add map
between flow {}
and flowOn
behavior will become differentPeter Farlow
10/26/2023, 1:54 PMwithContext
inside the flow { }
flow builder. If you try to call emit
inside the withContext
block, it will throw an exception. You should use flowOn if you want to change the dispatcher on which the flow executes the codemyanmarking
10/26/2023, 1:57 PMPeter Farlow
10/26/2023, 2:04 PM