Search code examples
androidmvvmandroid-architecture-components

Best practice MVVM pass Data from one Activity to another


What is the current best practice of passing Data from one activity (master) to another (detail).

  1. a possible approach could be to have a single view model class that's shared between the master and detail. When clicking on an item in the master activity the selected entry will be set to the view model. The detail activity, thereby can read the selected entry, because it's using the same view model.

  2. Pass the row-id of the selected object from the master-activity as an bundle-extra to the detail activity. The detail activity loads it's view model by using ViewModelProviders and afterwards passes the row-id to the view-model which loads the actual record.

  3. Initiale the view model before starting the detail activity and set the selected object directly to the initialized view model of the detail activity.

Input would be very much appreciated!


Solution

  • Your detail activity should be able to reconstruct itself from saved state. For example, with your detail in the foreground and the screen off, your entire app could be expunged from memory. When the screen is back on, Android will only start your detail activity and expect it to get what it needs from saved state.

    So, any design that relies on the master setting data into a singleton / global somewhere would not be great. Unclear to me exactly but it seems like that's what you might have been suggesting in (1) and (3).

    IMHO, set the row ID into the extras passed to the detail activity. Save / restore that row ID with detail save state. Let the detail activity build its own model based on the row ID. It makes the detail independent in that it won't depend on something else initializing some complex model before it can start. That makes it more modular and testable also.