0

I have two questions for a simple Fragment A -> Fragment B graph:

  1. Can I pass LiveData using safe args? If not, how can I listen the value changes in Fragment B from Fragment A?

  2. Can I pass lambda varible (function) using safe args (to act like a callback listener)?

Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • 2
    For first, You can share your ViewModel between fragments. Init this ViewModel in Activity and share between fragments. Now using the same ViewModel instance, we can observe live-data from both fragments. – Kishan Maurya Jan 21 '21 at 19:16
  • Is there a reason you're not using the [APIs specifically built for returning a result](https://developer.android.com/guide/navigation/navigation-programmatic#returning_a_result)? – ianhanniballake Jan 21 '21 at 19:39

1 Answers1

1

you cant pass a LiveData using safe args but you can use the Fragment Result API to listen value changes in other fragments

// in fragment A
setFragmentResultListener("requestKey") { requestKey, bundle ->
    // read bundle here
}
// in fragment B
setFragmentResult("requestKey", bundle)

it can be combined with your SafeArgs classes:

setFragmentResultListener("requestKey") { requestKey, bundle ->
    val args = MyFragmentArgs.fromBundle(bundle)
}
// Fragment B
setFragmentResult("requestKey", MyFragmentArgs(...).toBundle())
Sinner of the System
  • 2,558
  • 1
  • 8
  • 17