Nat Strangerweather
04/18/2023, 8:04 PMLeo Delon
04/19/2023, 11:54 AMby activityViewModels()
or 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 AMHugo Bernardi
04/20/2023, 9:22 AMstartDestination
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 :
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.ktNat Strangerweather
04/20/2023, 9:47 AM