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

Jetpack Compose navigate for result


I'm using the Jetpack Navigation library with the Compose version. I'm setting up navigation like it's shown here

I want to be able to navigate from screen A to screen B. Once B does something and pops off the back stack, it will then return a result that screen A can access.

I found a way to do this using Activities here but I want to avoid creating any extra activities and do this in compose.


Solution

  • From the Composable that you want to return data, you can do the following:

    navController.previousBackStackEntry
        ?.savedStateHandle
        ?.set("your_key", "your_value")
    navController.popBackStack()
    

    and then, from the source Composable, you can listen for changes using a LiveData.

    val secondScreenResult = navController.currentBackStackEntry
        ?.savedStateHandle
        ?.getLiveData<String>("your_key")?.observeAsState()
    ...
    secondScreenResult?.value?.let {
        // Read the result
    }