```private fun subscribeToViewModel() = lifecycleS...
# coroutines
v
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
You need multiple launch calls, or use
onEach
and
launchIn
👍 1
v
how does onEach differ from collect?
l
@Vincent Williams Look at the signature of both functions (including their modifiers), and their documentation.
v
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
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
ok cool. Its also convenient because I can use
catch
instead of the coroutine exception handler
didnt realize that function existed until now
l
Ah yes, I should also start using it myself, thanks for reminding me it exists!
v
ya Ive been wanting something like that for a while (thought the coroutineexceptionhandler was pretty messy) had no idea they already added it xD