Jetpack Compose Navigation Return Result

Setup Jetpack Compose Navigation.

Return Result

@Composablefun SelectPlaceScreen(viewModel: SelectPlaceViewModel = viewModel(), onBack: (Map<String, Any>?) -> Unit) {    Button(onClick = {        onBack(mapOf(            "placeId" to "hello1234"        ))    } {        Text("Back with result")    }}
fun onBack(data: Map<String, Any>? = null) {    if (data != null) {l        navController.previousBackStackEntry?.savedStateHandle?.let {            for ((key, value) in data) {                it.set(key, value)            }        }    }    navController.popBackStack()}

NavHost Composable

NavHost(navController = navController, startDestination = Screen.Home.route) {    composable("card?cardId={cardId}",        arguments = listOf(            navArgument("cardId") {                type = NavType.StringType                nullable = true                defaultValue = null            }        ))    { backStackEntry ->        CardScreen(            viewModel = hiltViewModel(),            cardId = backStackEntry.arguments?.getString("cardId"),            // maybe backStackEntry.savedStateHandle work as well?            savedStateHandle = navController.currentBackStackEntry?.savedStateHandle)     }}

Composable Screen which receive result

@Composablefun CardScreen(    viewModel: CardViewModel = viewModel(),    cardId: String? = null,    savedStateHandle: SavedStateHandle?,) {    if (savedStateHandle != null) {        val placeId by savedStateHandle.getLiveData<String>("placeId").observeAsState()        LaunchedEffect(placeId) {            placeId?.let {                // do something                savedStateHandle.remove<String>("placeId")            }        }    }}

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.