https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

julioyg

11/13/2019, 10:45 AM
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

nrobi

11/13/2019, 10:51 AM
You can use
kotlinx.coroutines.Dispatchers.Main
for the UI
s

sikri

11/13/2019, 10:55 AM
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

julioyg

11/13/2019, 11:27 AM
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

nrobi

11/13/2019, 11:28 AM
Yes it does,
launchOn()
calls
collect()
s

sikri

11/13/2019, 11:28 AM
It consumes
j

julioyg

11/13/2019, 11:29 AM
ohhhhh! cool
Thank you 🙂
s

sikri

11/13/2019, 11:30 AM
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

tseisel

11/13/2019, 2:24 PM
@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

julioyg

11/13/2019, 2:25 PM
thanks 🙂
2 Views