View model

AndroidX provides classes to implement the MVVM pattern.

The ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity/Fragment with the rest of the application.

Best practice:

  • view model shouldn’t know anything about Android
  • view model shouldn't have references to the views (view models and views have different life cycle)
  • don’t put hard logic in the ViewModel, just work with a repository, i.e with a class that manages multiple data sources like memory cache, web, db.

LiveData is an observable data holder class. Unlike a regular observable, it takes into account the lifecycle of other app components, such as activities, fragments, or services.

A LiveData object is usually stored within a ViewModel object.

class NameViewModel : ViewModel() {

    // Create a LiveData with a String
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    // ...
}
Add dependencies for viewmodel, lifecycle and live data

In most cases, an app component’s onCreate() method is the right place to begin observing a LiveData object.

class NameActivity : AppCompatActivity() {

    // Use the 'by viewModels()' Kotlin property delegate
    // from the activity-ktx artifact
    private val model: NameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // ...
        
        // Create the observer which updates the UI.
        val nameObserver = Observer<String> { newName ->
            // Update the UI, in this case, a TextView.
            nameTextView.text = newName
        }

        // Observe the LiveData, passing in this activity 
        // as the LifecycleOwner and the observer.
        model.currentName.observe(this, nameObserver)
    }
}
public class NameActivity extends AppCompatActivity {

    private NameViewModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ... 
        
        // Get the ViewModel
        model = new ViewModelProvider(this).get(NameViewModel.class);

        // Create the observer which updates the UI.
        final Observer<String> nameObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String newName) {
                nameTextView.setText(newName); // update the UI, in this case, a TextView.
            }
        };

        // Observe the LiveData, passing in this activity 
        // as the LifecycleOwner and the observer.
        model.getCurrentName().observe(this, nameObserver);
    }
}

Fragments can get the activity viewmodel via activityViewModels() method.

Share viewmodel with fragments

A fragment can define its own view model and share it with a child fragment.

Fragment viewmodel