navigator icon indicating copy to clipboard operation
navigator copied to clipboard

ViewModel for Navigation graph level

Open shakil807g opened this issue 2 years ago • 4 comments

is it possible to scope ViewModel to Navigation level currently?

shakil807g avatar Aug 29 '22 07:08 shakil807g

Is this question for navigator (deals with fragments) or navigator-compose (which deals with Composables)?

KaustubhPatange avatar Aug 30 '22 19:08 KaustubhPatange

@KaustubhPatange Sorry i didn't mention that, it is meant for navigator-compose

shakil807g avatar Aug 30 '22 21:08 shakil807g

You can! All you have to do is scope ViewModelStoreOwner to the parent Route. I'll update the docs to mention this, but for now take a look at following snippet.

val controller = rememberNavController<MenuItem>()
.... // your navigation setup

/* Note: controller.parentRoute could be null so make sure to handle that gracefully as well.
* Cases where it could be null? When your navigation is not a nested destination. */
val viewModel by viewModel(viewModelStoreOwner = controller.parentRoute) 

KaustubhPatange avatar Aug 31 '22 08:08 KaustubhPatange

@KaustubhPatange

You mean like this ? val viewModel = viewModel<DiscoverViewModel>(viewModelStoreOwner = controller.parentRoute?.lifecycleController!!)

shakil807g avatar Aug 31 '22 10:08 shakil807g

Yes, exactly!

KaustubhPatange avatar Sep 01 '22 06:09 KaustubhPatange