I found a little bit about this error here => ...
# compose-android
n
I found a little bit about this error here => "`You cannot access the NavBackStackEntry's ViewModels after the NavBackStackEntry is destroyed.`" <= on this channel, but I am not clear what causes it and how to avoid it. Is there any consensus on this nowadays?
l
This is because the ViewModels in a NavBackStackEntry are tied to the lifecycle of that entry. Once the entry is destroyed, the ViewModels are also destroyed and their data is lost. To prevent this, you can use a shared ViewModel between multiple fragments so that the data is not lost when the NavBackStackEntry is destroyed. To use a shared ViewModel, you can create it in your activity or parent fragment using the
by activityViewModels()
or
by navGraphViewModels()
delegate. Then, each fragment can access the same ViewModel using this delegate. Here's an example in Kotlin:
Copy code
// In your Activity or parent fragment
val myViewModel: MyViewModel by activityViewModels()

// In each fragment that needs to access the ViewModel
val myViewModel: MyViewModel by activityViewModels()
This way, when a NavBackStackEntry is destroyed, the ViewModel is still available to other fragments that need to access it.
n
Thank you for your reply. Are you talking about Navigation in Jetpack Compose?
h
We ran into this issue too. It was caused when
startDestination
of the
MainNavGraph
was changed on activity re-creation (i.e with "Don't keep activities" enabled in Developer Options). This startDestination was compute by a
StateFlow
in a
ViewModel
, but the value of the stateflow was changing (i.e
isConnected
was switching from true - value before activity was destroy - to false - initial value after activity re-creation, then true again - value collected) too fast, causing some unwanted navigation. Using savedStateHandled to restore startDestination correctly fixed this issue :
Copy code
isConnectedFlow.stateIn(
    scope = viewModelScope,
    started = SharingStarted.Lazily,
    initialValue = savedStateHandle.get<Boolean>(IsConnectedSaveStateHandleKey) ?: false, // here
)
Also, if you have a view model associated to a NavGraph, you may have to do something like this : https://github.com/Zhuinden/jetpack-navigation-ftue-compose-sample/blob/1225e30551[…]/jetpacknavigationftuecomposeexample/application/AppNavGraph.kt
n
Many thanks, will look into this!
365 Views