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

jean

01/07/2021, 8:31 AM
I have this (ugly) code that works :
Copy code
lifecycleScope.launch {
    viewModel.state.collect { updateState(it, binding) }
}
lifecycleScope.launch {
    viewModel.load()
}
I cannot have
viewModel.load()
inside the first block after
collect
since it never ends and if I put it before I miss a bunch of events. Is there a way to write this in a better way?
g

Giorgos Neokleous

01/07/2021, 9:38 AM
How about
launchIn
?
Copy code
lifecycleScope.launch {
    viewModel.state.onEach { updateState(it, binding) }.launchIn(lifecycleScope)

    viewModel.load()
}
You can even take out the whole observation from the launch block with launchIn
j

jean

01/07/2021, 10:01 AM
that’s a bit better indeed, thanks 🙂