https://kotlinlang.org logo
#compose
Title
# compose
z

zoha131

11/13/2020, 3:47 PM
Can I create
viewModel
scoped to a
composable
using
navigation-compose
?
i

Ian Lake

11/13/2020, 4:58 PM
That's what you get already when you use
viewModel()
inside those composables
n

nrobi

11/13/2020, 5:36 PM
@Ian Lake correct me if I'm wrong but AFAIK that way it will be scoped to the Fragment/Activity from where you call
setContent
, since it has to be tied to a
ViewModelStoreOwner
i

Ian Lake

11/13/2020, 5:43 PM
You are indeed wrong 😄 Navigation provides its own
ViewModelStoreOwner
for each
NavBackStackEntry
as per the docs: https://developer.android.com/guide/navigation/navigation-programmatic#navbackstackentry
NavHost
overrides the ambients so that
viewModel()
within the composable uses that scoped owner
👍 1
This is mentioned in the Navigation Compose release notes: https://developer.android.com/jetpack/androidx/releases/navigation#compose-1.0.0-alpha01
👍 1
This ability to scope a ViewModel to individual composables is indeed a separate problem that is not yet solved, you are right about that part though
n

nrobi

11/13/2020, 5:50 PM
🎊 Ahh, thanks a lot for the clarification, didn't know about this 😁
z

zoha131

11/13/2020, 6:26 PM
I was reading the documentation and found nothing there about viewmodel. Now I am clear. thanks @Ian Lake
4 Views