Is there a way to reassign the `ViewModelStoreOwne...
# compose
n
Is there a way to reassign the
ViewModelStoreOwner
of a
hiltViewModel()
? 😛 Let’s say the user is in
ScreenA
and navigate to
ScreenB
. In
ScreenB
, I’m creating a viewmodel using
hiltViewModel()
. So, the scope of this viewmodel is
ScreenB
. Now, from
ScreenB
, I want to open
ScreenC
, pop
ScreenB
(therefore, the stack is
ScreenA
and
ScreenC
), but reuse the viewmodel created in
ScreenB
. Is it possible? 🤔 (I wouldn’t create the viewmodel in
ScreenA
😞)
i
No, it sounds like your screen b ViewModel should have been wider scoped to begin with (i.e., to a navigation graph that contains at least both B and C)
But really, a ViewModel should be tightly tied to only display the data relevant to that screen; you probably want a completely separate shared ViewModel rather than co-opting a screen specific one
n
I understand… It’s possible to create one viewmodel per screen. But I would have to do an API call twice unnecessarily 🤷‍♂️
Anyways… I’ll let my viewmodel scope more wider
c
Another option would be to hold the state of ViewModelB in a single serializable class, which gets passed in serialized form from ScreenB to ScreenC (either JSON passed as a string, or as a Parcelable class). Alternatively, cache the API call in a local DB, and have both screens read from the DB instead of directly displaying API data. Either class then calls to a "repository" which handles the caching logic internally, and neither the DB nor the API are directly exposed to the VM
i
Yeah, a shared cache accessed by the two ViewModels (either as part of your repository layer or as a separate thing) seems like a good layering practice in general
👆 2