There are multiple ways communicating between fragments? When should we use them?

44 Views Asked by At

There are multiple ways to communicate between fragments.

  1. Shared ViewModel
  2. Fragment Result API
  3. Navigation Component
    a. Safe Args
    b. Arguments(Bundle)
  4. 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.

1

There are 1 best solutions below

0
Nazarii Moshenskyi On

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's Parcelable or a list of Parcelables. 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 ViewModel might 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 ViewModel if 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.