Architecture-samples: todo鈥憁vvm鈥憀ive: Activity with multiple fragments communication

Created on 21 Mar 2018  路  1Comment  路  Source: android/architecture-samples

Hi,
Assume we have an Activity holding a TabLayout where every TabItem (expected are 4) represents a Fragment and every Fragment have to communicate with the Activity.
I am considering using separate ViewModels for at least 2 of the Fragments. To achieve that I have the following options:

  1. One "big" shared ViewModel
  2. The Activity will observe multiple ViewModels
  3. Direct communication between Fragment and Activity

What would you suggest?
And where would you suggest to place a BroadcastReceiver, i.e. for BluetoothAdapter state: in ViewModel (although considering:

Don鈥檛 let ViewModels (and Presenters) know about Android framework classes)

or Activity?
Thanks in advance!

Most helpful comment

It is not an obligation for the Activity to observe only one ViewModel.
In fact, you can easily decide to split ViewModels into smaller chunks when they tend to grow big.

For your example, you could end up having 3 ViewModels used in your Activity:
1 ViewModel that encompasses Activity, TabItem1 and TabItem2
1 ViewModel for TabItem3 logic and TabItem3<->Activity communication (so Activity can observe changes that would have been initiated via TabItem3)
1 ViewModel for TabItem4 logic and TabItem4<->Activity communication (so Activity can observe changes that would have been initiated via TabItem4)

>All comments

It is not an obligation for the Activity to observe only one ViewModel.
In fact, you can easily decide to split ViewModels into smaller chunks when they tend to grow big.

For your example, you could end up having 3 ViewModels used in your Activity:
1 ViewModel that encompasses Activity, TabItem1 and TabItem2
1 ViewModel for TabItem3 logic and TabItem3<->Activity communication (so Activity can observe changes that would have been initiated via TabItem3)
1 ViewModel for TabItem4 logic and TabItem4<->Activity communication (so Activity can observe changes that would have been initiated via TabItem4)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AeroEchelon picture AeroEchelon  路  4Comments

ghost picture ghost  路  3Comments

AnirudhaAgashe picture AnirudhaAgashe  路  7Comments

BeQuietLee picture BeQuietLee  路  3Comments

aitorvs picture aitorvs  路  4Comments