jean
10/22/2020, 8:08 AMStateFlow object from the view model. The view can then simply collect the updates and do whatever it needs. Something like this :
data class ViewState {
val isLoading: Boolean,
@StringRes val error: Int,
val items: List<Any>
}
class SomeViewModel : ViewModel() {
private val _state = MutableStateFlow<ViewState>()
val state: StateFlow<ViewState> = _state
// All the logic to update _state
}
class SomeFragment : Fragment() {
...
override fun onViewCreated(...) {
lifeCycleScope.launch {
viewModel.state.collect { state ->
// update the view
}
}
}
}
2/ Instead of using a StateFlow and a data class containing all the data, use a sealed class to make “differential updates”
sealed class ViewState {
data class IsLoading(val isLoading: Boolean)
data class Error (@StringRes val error: Int)
data class ItemsLoaded(val items: List<Any>)
}
class SomeViewModel : ViewModel() {
private val channel = Channel<ViewState>()
val state: Flow<ViewState> = channel.receiveAsFlow()
// All the logic to offer/emit new value
}
class SomeFragment : Fragment() {
...
override fun onViewCreated(...) {
lifeCycleScope.launch {
viewModel.state.collect { state ->
// update the view
}
}
}
}
what are the +/- to use one or the other solution? I feel the second option let me have a better overall control on how to update the view since I can react to specific events.allan.conda
10/22/2020, 8:14 AMI feel the second option let me have a better overall control on how to update the view since I can react to specific events.Really? I feel the other way around. How will you show an error without hiding the items? 🙂
allan.conda
10/22/2020, 8:15 AMflosch
10/22/2020, 8:15 AMsealed class as view state. of course it can work with `sealed class`es, but I think its easier, more concise and more deterministic with a data class .
If a loading->error/success state is needed, that just have the sealed class as a val in your state data classjean
10/22/2020, 8:17 AMstate is Error and then simply do whatever I need to do to show an errorjean
10/22/2020, 8:18 AMupdateType the the general data class to obtain sort of the same possibility 🤔allan.conda
10/22/2020, 8:26 AMthe state flow doesn’t really tells me why there has been an update.because state flow is for state and not events or updates. if/else is just vanilla
when
if you have an Error State sealed you would only be able to render it’s properties.
you don’t need updateType as well, you can just render an error if it’s available.
data class State(
val items: List<Item> = emptyList()
val error: Error?
)
@Composable fun Screen(state: State) {
error?.{ Text(message = it) }
}
So State class is not about updating some state, It is the state, that you render to view.jean
10/22/2020, 8:31 AMallan.conda
10/22/2020, 8:53 AMAdam Powell
10/22/2020, 2:39 PMAdam Powell
10/22/2020, 2:41 PMjean
10/22/2020, 6:51 PMGeorge Theocharis
10/23/2020, 8:38 PMjean
10/26/2020, 7:18 AMjean
01/11/2023, 9:32 AM