Good morning (for some at least i guess :sweat_smi...
# coroutines
j
Good morning (for some at least i guess 😅 ) I'm starting to use flows and I wonder how can i specify the thread the function I pass onto
collect
is executed. I'm trying:
Copy code
launch(UI) {
  flow.collect {
    // i was hoping this was executed in UI
  }
should that be running in the UI Dispatcher?
n
You can use
kotlinx.coroutines.Dispatchers.Main
for the UI
s
You don’t need to launch { flow.collect { } }, because you would have callabacks and too many scopes Instead, you can launch flow in some scope, for example:
Copy code
flow
    .onEach { doSmth(it) }
    .launchOn(Dispatcher.Main)
😮 1
j
thanks 🙂
@sikri that doesn't consume the the value, does it?
it just creates new flow that does that on when there is a new item
n
Yes it does,
launchOn()
calls
collect()
s
It consumes
j
ohhhhh! cool
Thank you 🙂
s
Because other way we would have too many scopes
Copy code
launch(UI) {
   flow.collect {
       too many scopes
   }
}
https://github.com/Kotlin/kotlinx.coroutines/blob/8d8b6eb8a1186ae987610a31ac441d107d04b034/kotlinx-coroutines-core/common/src/flow/terminal/Collect.kt
Copy code
@ExperimentalCoroutinesApi // tentatively stable in 1.3.0
public fun <T> Flow<T>.launchIn(scope: CoroutineScope): Job = scope.launch {
    collect() // tail-call
}
t
@julioyg When collecting a flow with
collect
, the passed block invoked for each collected item, and * always in the context of the current coroutine*. Note that
UI
is deprecated in favor of
Dispatchers.Main
. If you want some flow operations to be executed on another Thread/Dispatcher, you could use the
flowOn
operator. Note that unlike Rx `subscribeOn`/`observeOn`,
flowOn
is only applied to upstream operations.
j
thanks 🙂