I’m trying to ‘return a result’ via Compose - sett...
# compose
t
I’m trying to ‘return a result’ via Compose - setting a value on the
SavedStateHandle
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 thread
👀 1
So, the user starts on the Home screen. The Home screen contains a ViewModel, which stores whether the user has entered ‘guest mode’ or not.
Copy code
@Composable
fun HomeScreen(
    viewModel: HomeViewModel = hiltViewModel()
        ...
Copy code
@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:
Copy code
NavHost(
    ..
) {
    homeGraph(
        onNavigateToLogin = {
            navController.navigate(LoginDestination.route)
        }
    )
    loginGraph(
        navController = navController,
        onEnterGuestMode = {
            navController.previousBackStackEntry?.savedStateHandle?.set(HomeViewModel.KEY_GUEST_MODE, true)
            navController.popBackStack()
        }
    )
}
Copy code
fun NavGraphBuilder.homeGraph(
    onNavigateToLogin: () -> Unit
) {
    composable(route = HomeDestination.route) {
        HomeScreen(
            onNavigateToLogin = onNavigateToLogin
        )
    }
}
Copy code
fun NavGraphBuilder.loginGraph(
    navController: NavHostController,
    onEnterGuestMode: () -> Unit
) {
    composable(route = LoginDestination.route) {
        LoginScreen(
            onEnterGuestMode = onEnterGuestMode
        )
    }
...
--- The question is: How can the
onEnterGuestMode
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?
i