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

Vincent Williams

08/20/2020, 4:52 PM
Copy code
private fun subscribeToViewModel() = lifecycleScope.launch(Dispatchers.Main) {
        viewModel.viewState.collect { onViewStateEvent(it) }
        viewModel.navigationEvents.collect { onNavigationEvent(it) }
    }
This code doesnt seem to work. It only collects the first flow. Do I need to have two separate
launch
statements? Is there an easier way to do this as it gets a little messy with 3 or 4 flows
l

louiscad

08/20/2020, 5:13 PM
You need multiple launch calls, or use
onEach
and
launchIn
👍 1
v

Vincent Williams

08/20/2020, 5:20 PM
how does onEach differ from collect?
l

louiscad

08/20/2020, 5:56 PM
@Vincent Williams Look at the signature of both functions (including their modifiers), and their documentation.
v

Vincent Williams

08/20/2020, 6:54 PM
sorry to rephrase, I understand how the actual methods differ, but is there any functional difference between using onEach and launchIn vs just collect
or are both of those equivalent ways of doing the same thing?
l

louiscad

08/20/2020, 6:55 PM
Yes,
collect
suspends while collecting items
But
launch
+
collect
is equivalent to
onEach
+
launchIn
, unless you care about each CPU cycle, in which case there's a very very tiny difference. So I'd pick
onEach
+
launchIn
when more convenient.
v

Vincent Williams

08/20/2020, 6:59 PM
ok cool. Its also convenient because I can use
catch
instead of the coroutine exception handler
didnt realize that function existed until now
l

louiscad

08/20/2020, 7:00 PM
Ah yes, I should also start using it myself, thanks for reminding me it exists!
v

Vincent Williams

08/20/2020, 7:01 PM
ya Ive been wanting something like that for a while (thought the coroutineexceptionhandler was pretty messy) had no idea they already added it xD
2 Views