Bradleycorn
07/22/2024, 10:33 PMvar uiState: InitializationState by mutableStateOf(Loading)
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState
.onEach { uiState = it }
.collect()
}
}
I'm curious if there's a particular reason why they use onEach
to update the state value?
Why not use the collect method directly, like the example below?
var uiState: InitializationState by mutableStateOf(Loading)
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { uiState = it }
}
}
The only thing I can really think of is that they did it that way for "future proofing", in case they want to add additional functional method calls (map, filter, etc) to the flow.ephemient
07/23/2024, 1:27 AMjw
07/23/2024, 1:45 AMjw
07/23/2024, 1:46 AMlifecycleScope.launch
as well...Alex Vanyo
07/23/2024, 5:29 PM.onEach { /* ... */ }.collect()
vs .collect { /* ... */ }
that much in either direction, I don’t think there’s a strong reason either way. They should be entirely equivalent, if you prefer one over the other, than use that.
I don’t really think “future-proofing” is really a consideration, it’s a one line change to swap to the other if needed for some reason in the future.Bradleycorn
07/23/2024, 6:12 PMAlex Vanyo
07/23/2024, 6:18 PM