Johan Reitan
11/30/2021, 10:24 AMViewModel
. I expected that I could use the SavedStateHandle
injected in my ViewModel
to listen to the navigation result, but I see that this SavedStateHandle
is not the same as the one from the NavBackStackEntry
that holds the result. Details in thread 🧵Johan Reitan
11/30/2021, 10:29 AMsavedStateHandle
in my `ViewModel`:
@HiltViewModel
class MyViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
)
was the same as the savedStateHandle
from the NavBackStackEntry
that was used as the ViewModelStoreOwner
to create the `ViewModel`:
composable("route") {
val viewModel: MyViewModel = hiltViewModel(
remember { navController.getBackStackEntry("route") }
)
val savedStateHandle = navController.getBackStackEntry("route").savedStateHandle
MyComposable(/* args */)
}
… but it’s not.
Is there a way to accomplish this without having to update properties on the ViewModel
after it’s been created?Ian Lake
11/30/2021, 6:08 PMIan Lake
11/30/2021, 6:09 PMnavBackStackEntry.savedStateHandle
does is create its own ViewModel and get its SavedStateHandle: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:navigation/navigation-common/src/main/java/androidx/navigation/NavBackStackEntry.kt;l=117 so yeah, it'll be a different SavedStateHandleIan Lake
11/30/2021, 6:11 PMIan Lake
11/30/2021, 6:16 PMIan Lake
11/30/2021, 6:17 PMJohan Reitan
12/01/2021, 8:45 AMJohan Reitan
12/01/2021, 8:45 AMJohan Reitan
12/01/2021, 8:46 AMcomposable("route") {
val viewModel: MyViewModel = hiltViewModel()
LaunchedEffect(viewModel, navController) {
val savedStateHandle =
navController.getBackStackEntry("route").savedStateHandle
savedStateHandle
.getLiveData<String?>("result")
.asFlow()
.filterNotNull()
.collect {
viewModel.onResult(it)
savedStateHandle["result"] = null
}
}
MyComposable(/* args */)
}