Search code examples
androidandroid-jetpack-composeandroid-viewmodelandroid-navigation

Controlling navigation from viewmodel


My NavHost and all of my navigation logic is in jetpack compose. I was wondering, is there any way to navigate (using navController) to a certain page when my viewmodel initializes?

If that is not possible, are there any workarounds?


Solution

  • Build flow like this

    This is your composable

    val viewModel: AAAViewModel = viewModel()
    val state by viewModel.screenState.collectAsState()
    
    LaunchedEffect(key1 = state.isComplete) {
        if (state.isComplete) {
            //navigate to your required screen but first reset variable so when you came back it doesnt get stuck in loop
            viewModel.clearCompleteVariable()
            navController.navigate(PinScreenDestination)
        }
    }
    

    Your view model

    data class AAAScreenState(
        val isComplete: Boolean = false,
    )
    
    class MyViewModel : ViewModel() {
        private val _screenState = MutableStateFlow(AAAScreenState())
        val screenState = _screenState.asStateFlow()
    
        fun testFunc() =
            _screenState.update { it.copy(isComplete = true) }
    
        fun clearCompleteVariable() =
            _screenState.update { it.copy(isComplete = false) }
    }