Fun with ViewModel and LiveData: Sending Informations between Fragments

In Android development, there are a few different ways to send informations between one fragment to another. As of September 2020, the recommended way to allow for this communication is to use LiveData exposed by a shared ViewModel.

The steps are relatively simple. Suppose that we want to send data from Fragment A to Fragment B:

  1. Create a ViewModel
  2. Have Fragment A and Fragment B share that same ViewModel.
  3. Create a LiveData inside the ViewModel to contain the data that’s to be passed from A to B.
  4. Assign or update value to the LiveData object inside Fragment A, usually with the help of a public method inside the ViewModel to assign or update the value.
  5. Have Fragment B observe the LiveData inside it onCreate() , and make use of the data there.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s