Instantly share code, notes, and snippets.
Last active
August 8, 2021 16:11
NavHostWithCustomNavigatorExample.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun NavHostExample( | |
navController: NavHostController = rememberNavController(), | |
navigator: Navigator = get(), | |
) { | |
val lifecycleOwner = LocalLifecycleOwner.current | |
val navigatorState by navigator.navActions.asLifecycleAwareState( | |
lifecycleOwner = lifecycleOwner, | |
initialState = null | |
) | |
LaunchedEffect(navigatorState) { | |
navigatorState?.let { | |
it.parcelableArguments.forEach { arg -> | |
navController.currentBackStackEntry?.arguments?.putParcelable(arg.key, arg.value) | |
} | |
navController.navigate(it.destination, it.navOptions) | |
} | |
} | |
NavHost(navController, startDestination = NavigationDestinations.firstScreen) { | |
composable(route = NavigationDestinations.firstScreen) { | |
FirstScreen() | |
} | |
composable(route = NavigationDestinations.secondScreen) { | |
SecondScreen() | |
} | |
composable( | |
route = "${NavigationDestinations.thirdScreen}/{someStringArgument}", | |
arguments = listOf(navArgument("someStringArgument") { type = NavType.StringType }) | |
) { | |
val someStringArgument = backStackEntry.arguments?.getString("someStringArgument") | |
val someParcelableObject = | |
navController.previousBackStackEntry?.arguments?.getParcelable<SomeParcelableClass>( | |
"firstArg" | |
) | |
ThirdScreen( | |
someStringArgument = someStringArgument, | |
someParcelableObject = someParcelableObject | |
) | |
} | |
} | |
} | |
@Composable | |
fun FirstScreen( | |
viewModel: FirstScreenViewModel = getViewModel() | |
) { | |
... | |
} | |
@Composable | |
fun SecondScreen( | |
viewModel: SecondScreenViewModel = getViewModel() | |
) { | |
... | |
} | |
@Composable | |
fun ThirdScreen( | |
viewModel: ThirdScreenViewModel = getViewModel(), | |
someStringArgument: String, | |
someParcelableObject: SomeParcelableClass | |
) { | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment