Navigation 3 in Jetpack Compose requires explicit setup to scope ViewModels per backstack entry. The key is using rememberViewModelStoreNavEntryDecorator() alongside rememberSaveableStateHolderNavEntryDecorator() in NavDisplay. This decorator leverages NavEntry.contentKey to uniquely identify each ViewModel instance, eliminating the need to manually supply unique key strings. For passing route arguments into ViewModels, both a standard ViewModelProvider.Factory pattern and Hilt Assisted Injection approach are covered with code examples. Forcing re-initialization when the same screen receives new data requires passing the key explicitly to the viewModel() call. A known limitation is that ViewModelStore does not currently support state retention when switching between multiple backstacks.

5m read timeFrom proandroiddev.com
Post cover image
Table of contents
🍔 The Missing Link: rememberViewModelStoreNavEntryDecorator()🍔 Passing Values via ViewModels🍔 Detecting Key Changes to Re-initializeGet chanzmao ’s stories in your inbox🍔 Verifying the Lifecycle🍔 Summary🍔 Related ArticlesStop Fighting Multiple BackStacks in Jetpack Compose Navigation3Jetpack Compose State Survival Guide: From remember to rememberNavBackStack

Sort: