Can 2 views share the same viewmodel without loosing the state, so both can mutate it?
👌 3
i
Issa
12/02/2022, 1:01 PM
can you explain a bit further what do you mean by two views? do you mean two composables ?
e
Elio Maroun
12/02/2022, 1:20 PM
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
Issa
12/02/2022, 1:27 PM
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
mattinger
12/02/2022, 7:52 PM
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
Tariyel Islami
12/03/2022, 7:58 PM
if i understood correctly you can use it like this