Improving state encapsulation in ViewModel
Let's have a look at how the UI state is defined in the RestaurantsViewModel class, as follows:
class RestaurantsViewModel() : ViewModel() {
…
val state = mutableStateOf(RestaurantsScreenState(
restaurants = listOf(),
isLoading = true))
…
}
Inside the RestaurantsViewModel, we are holding the state within the state variable with the MutableState<RestaurantsScreenState> inferred type. This variable is public, so inside the UI layer, from within the RestaurantsScreen() composable, we can consume it by accessing the viewModel variable and directly obtaining the state object, as follows:
@Composable
fun RestaurantsScreen(onItemClick: (id: Int) -> Unit) {
val viewModel: RestaurantsViewModel = viewModel()
...