I came across a sample application (Google's NowIn...
# coroutines
b
I came across a sample application (Google's NowInAndroid app), that has this bit of code to collect a StateFlow:
Copy code
var 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?
Copy code
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.
e
I haven't looked into the history here but I've seen other examples when code that was .launchIn(lifecycleScope) was modified to be wrapped in repeatOnLifecycle after that was introduced
j
Yeah that may be true, but it would have been needless-bordering-on-incorrect even then as the subscription to the stateflow is pointless to keep alive longer than needed (as opposed to some kind of cold flow).
unless they also did not have the
lifecycleScope.launch
as well...
a
I would not read into
.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.
👍 1
b
Thanks @Alex Vanyo that's what I was looking for ... Was there a particular reason it was written the way that it was, or just "author's choice". Sounds like it was author's choice.
a
Author’s choice for sure