Can 2 views share the same viewmodel without loosi...
# compose
e
Can 2 views share the same viewmodel without loosing the state, so both can mutate it?
👌 3
i
can you explain a bit further what do you mean by two views? do you mean two composables ?
e
i have a view where I have a list of appointments based on a certain date, and another screen/view where I pick or change the date of the first screen.
i
I think it’s possible to consume the state published by the ViewModel in the first screen all you have to do is observe it. • DatePickerComposable(onDateChanged: () -> Unit) ◦ the callback should be something like
viewModel.changeDate(newDate: Date)
• AppointmentsComposable(state: ViewModelState) ◦ you should listen to this state and your composable will recompose should this state change
m
It's definitely possible. However, you have to make sure that the ViewModelStoreOwner of the ViewModel lives outside the scope of either of those composables. A good example of this would be when using the navigation component, you can have a nav graph scoped view model which could be accessible from any composable destination. This is not specifically a compose thing, but rather a standard android ViewModelStoreOwner thing.
t
if i understood correctly you can use it like this
Copy code
@OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.ScreenNavigation(
    viewModel : MainViewModel = hiltViewModel()
) {

    composable(route = "A") {
        AScreen(
            viewModel = viewModel
        )
    }

    composable(route = "B") {
        BScreen(
            viewModel = viewModel
        )
    }
}