Tim Malseed
09/08/2022, 12:24 PMSavedStateHandle
of the previousBackStackEntry
and then popping the backstack.
But, the SavedStateHandle
that I want to interact with belongs to the initial screen’s ViewModel
, and I sense that this is not the same instance as the SavedStateHandle
found on the previousBackStackEntry
I suspect this has something to do with scoping ViewModels
, but I’ve tried a few things and I’m out of ideas. Code in threadTim Malseed
09/08/2022, 12:29 PM@Composable
fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel()
...
@HiltViewModel
class HomeViewModel @Inject constructor(
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val guestMode: StateFlow<Boolean> = savedStateHandle.getStateFlow(KEY_GUEST_MODE, false)
...
Under certain conditions, the user is navigated to the ‘Login’ screen. They can then choose to enter ‘guest’ mode, which attempts to update the SavedStateHandle
belonging to the HomeViewModel
, and then pop the LoginScreen off the stack, returning the user to the HomeScreen.
The NavHost looks like so:
NavHost(
..
) {
homeGraph(
onNavigateToLogin = {
navController.navigate(LoginDestination.route)
}
)
loginGraph(
navController = navController,
onEnterGuestMode = {
navController.previousBackStackEntry?.savedStateHandle?.set(HomeViewModel.KEY_GUEST_MODE, true)
navController.popBackStack()
}
)
}
fun NavGraphBuilder.homeGraph(
onNavigateToLogin: () -> Unit
) {
composable(route = HomeDestination.route) {
HomeScreen(
onNavigateToLogin = onNavigateToLogin
)
}
}
fun NavGraphBuilder.loginGraph(
navController: NavHostController,
onEnterGuestMode: () -> Unit
) {
composable(route = LoginDestination.route) {
LoginScreen(
onEnterGuestMode = onEnterGuestMode
)
}
...
Tim Malseed
09/08/2022, 12:32 PMonEnterGuestMode
callback on the loginGraph
access the SavedStateHandle
belonging to the HomeViewModel
.
Or alternatively, how can the HomeViewModel
use the same SavedStateHandle
instance associated with the Home
destination’s backStackEntry?Ian Lake
09/08/2022, 2:53 PM