hi guys. working with Jetpack Navigation and Compo...
# compose-android
p
hi guys. working with Jetpack Navigation and Compose and I have a question related to NavHost implementation and viewModel’s lifecycle.
I have a tablet screen composable including a main screen with a side panel. The side panel contains a
NavHost
with two composables A, B. When I remove the side panel with a plain if, the viewModel of the active side panel never calls
onCleared()
and it is kept alive. I noticed the viewModels are cleared successfully when switching between A and B but not when removing the
NavHost
. Is there a way to clear them properly?
s
The VM is scoped to the ViewModelStoreOwner that is found in the local most likely. And that's probably the destination of your outer NavHost, and that one isn't cleared in this case, so the VM won't be cleared
Are you following the suggestions from here

https://youtu.be/LTLQhC6VadI?si=bnkfiSol7jBFywxF

? Do you need the nested NavHost for your use case?
👀 1
p
thanks for the video, in mobile you can navigate from Main to A or B and go back. A top level NavHost solves that as shown in the video. Then in tablet the idea is to reuse those A and B in a side panel. Both A and B has their own viewModel.
In the view system, I usually had a top level fragment with an internal fragment for the side panel. When the internal fragment was removed, its viewmodel was cleared.
so I understand the viewmodel in the side bar won’t be removed until the top level navhost is cleared, even if the nested composable is not there anymore.
s
To me it looks like the two screens are on the same compose destination, so they have the same ViewModelStoreOwner, so they won't get cleared individually. When you say "... Until the top level NavHost is cleared", that's not quite what I said, each destination on that NavHost is their own VMStoreOwner, so that destination needs to be popped for the VMs scoped to it to be cleared. Afaik there isn't a way atm to scope a VM to an arbitrary Composable like you wanna do here. Here's a relevant issue https://issuetracker.google.com/issues/165642391 tl;dr: you probably want something other than an AACVM to hold that screen's state. Or to have one VM for both of those screens at the same time, which will be persisted even if the child destination is popped.
p
Thanks, I’ll take a look at that. Thanks again for the answer