In this blog post I show you 2 ways of how to call code that depends on multiple LiveData sources.
You should be familiar with the following topics to fully understand this article:
- Android ViewModel, LiveData, Observer
Let’s look at the following ViewModel:
data2 and our
function that performs an action that requires the value of
data2 to be present.
Now, to execute the code in the function, we can add an observer for
data2 and just call the code of our original
function in it. We also attach it to
data2 , so whenever one of our LiveData’s changes, our code will run and we achieved our goal.
An alternative way is to create a MediatorLiveData instance out of our two LiveData’s and attach the observer to it. I created a helper function in order to do this with multiple LiveData’s: