Update: as part of Navigation 2.3.0, Navigation adds explicit support for returning a result with a specific section on returning a result from a Dialog destination as an alternative to using a shared ViewModel.
Previous answer:
The recommended pattern for communicating between Fragments with the Navigation Architecture Components is via a shared ViewModel
- a ViewModel
that lives at the Activity level achieved by retrieving the ViewModel
using ViewModelProvider(getActivity())
As per the documentation, this offers a number of benefits:
- The activity does not need to do anything, or know anything about this communication.
- Fragments don't need to know about each other besides the
SharedViewModel
contract. If one of the fragments disappears, the other one keeps working as usual.
- 每个片段都有自己的生命周期,不受另一个片段生命周期的影响.如果一个片段替换了另一个片段,UI将继续工作,没有任何问题.
您还可以使用navigation graph scoped ViewModel在比整个活动更小的范围内共享ViewModel.