There are multiple ways to communicate between fragments.
- Shared ViewModel
- Fragment Result API
- Navigation Component
a. Safe Args
b. Arguments(Bundle) - Custom scoped ViewModel by using dagger2 dependency injection (ViewModel is same / Singleton in the same scope)
I am confused which approach should be used in which scenario?
Communicating between fragments in Android.
You might want to use Fragment Result API and other
Bundle-related approaches when you pass a small amount of data because you might not want to serialize and deserialize a big chunk of data if it'sParcelableor a list ofParcelables. And I believe it has some size limit.But it's not a problem for well-designed apps.
The problem to keep in mind is that only a single listener and result can be registered to the given key. If more than one listener is registered for the same key, it will be replaced with the latest one.
Shared
ViewModelmight be okay for you unless it's a single-activity application and you scope it with an activity provider to be able to share it for fragments, and it will lay in memory as a singleton. Holding it in RAM when it's not needed seems to be a very stupid approach.Do you want to hold shared data inside a
ViewModelif it's rather big? You should keep in mind the separation of concerns when using this approach. It might be ok if there's a relatively small logic behind it, but sometimes it might be too much.