Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data to previous composable in Android Compose

I will take a simple sample.

I have 2 Screens: Screen A and Screen B. From Screen A, I open Screen B. And when I return Screen B to Screen A, I want to transfer data back to Screen A.

With Android Fragment, I can use Shared ViewModel or Fragment Result API to do this. But with Android Compose, the Fragment Result Api is not in Compose. With using Shard ViewModel, what lifecycle do I have to attach Shared ViewModel so it can keep alive? Activity, ... or something else.

Or is there another way to do this?

like image 736
Dương Minh Avatar asked Dec 06 '25 17:12

Dương Minh


1 Answers

If you use jetpack navigation, you can pass back data by adding it to the previous back stack entry's savedStateHandle. (Documentation)

Screen B passes data back:

composable("B") {
  ComposableB(
    popBackStack = { data ->
      // Pass data back to A
      navController.previousBackStackEntry
        ?.savedStateHandle
        ?.set("key", data)

      navController.popBackStack()
    }
  )
}

Screen A Receives data:

composable("A") { backStackEntry ->
  // get data passed back from B
  val data: T by backStackEntry
    .savedStateHandle
    .getLiveData<T>("key")
    .observeAsState()

  ComposableA(
    data = data,
    navToB = {
      // optional: clear data so LiveData emits
      // even if same value is passed again
      backStackEntry.savedStateHandle.remove("key")
      // navigate ...
    }
  )
}

Replace "key" with a unique string, T with the type of your data and data with your data.

like image 116
Noah Avatar answered Dec 08 '25 07:12

Noah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!