oday
07/03/2022, 1:07 PMAdam Powell
07/03/2022, 2:03 PMAdam Powell
07/03/2022, 2:04 PModay
07/03/2022, 3:05 PModay
07/03/2022, 3:06 PMlifecycleScope.launchWhenCreated {
viewModel.uiState.collect {
if (it.authenticated) {
setContent {
Home()
}
} else {
setContent {
Authentication()
}
}
}
}
oday
07/03/2022, 3:06 PMAdam Powell
07/03/2022, 3:06 PModay
07/03/2022, 3:07 PModay
07/03/2022, 3:07 PModay
07/03/2022, 3:08 PModay
07/03/2022, 3:08 PModay
07/03/2022, 3:08 PMAdam Powell
07/03/2022, 3:08 PMdistinctUntilChanged
Adam Powell
07/03/2022, 3:09 PMAdam Powell
07/03/2022, 3:10 PModay
07/03/2022, 3:14 PModay
07/03/2022, 3:14 PModay
07/03/2022, 3:14 PModay
07/03/2022, 3:16 PMNote that any instance of StateFlow already behaves as ifoperator is applied to it, so applyingdistinctUntilChanged
to adistinctUntilChanged
has no effect. See StateFlow documentation on Operator Fusion. Also, repeated application ofStateFlow
operator on any flow has no effect.distinctUntilChanged
Adam Powell
07/03/2022, 3:16 PMOG
07/07/2022, 5:44 AMviewModel.uiState.map { it.authenicated }.distinctUntilChanged().collect { .... }
And if you wanted to specify some default value here and still use a State flow, then just tack on stateIn()
before collect()
It seems like the logic in your VM runs once then emits result so your UI shows the appropriate UI/composable given the authentication result. If this is something you want to only execute once, then it's still part of your app/view state, you may just want to call into the VM to mark that you consumed and handled this state change.
Otherwise, it seems like how you have it written should already be fine, even if the view state was emitted several times due to other property changes but with the same authenticated value. Because compose is already smart enough to know if a property it's consuming changed or not and if needs to recalculate/redraw etc.