Nat Strangerweather

04/18/2023, 8:04 PM
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?

Leo Delon

04/19/2023, 11:54 AM
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()
by navGraphViewModels()
delegate. Then, each fragment can access the same ViewModel using this delegate. Here's an example in Kotlin:
// 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.

Nat Strangerweather

04/20/2023, 8:26 AM
Thank you for your reply. Are you talking about Navigation in Jetpack Compose?

Hugo Bernardi

04/20/2023, 9:22 AM
We ran into this issue too. It was caused when
of the
was changed on activity re-creation (i.e with "Don't keep activities" enabled in Developer Options). This startDestination was compute by a
in a
, but the value of the stateflow was changing (i.e
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 :
    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 :[…]/jetpacknavigationftuecomposeexample/application/AppNavGraph.kt

Nat Strangerweather

04/20/2023, 9:47 AM
Many thanks, will look into this!


05/31/2023, 2:08 PM
@Hugo Bernardi this problem still very big. If I just have
what should I do?