I am using an AsyncTask in my repository which is used to set the LiveData in the repository. How do I observe this LiveData from my ViewModel using Transformations?
Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.
Main + viewModelJob) private val _user = MutableLiveData<User>() val user: LiveData<User> get() = _user val email = MutableLiveData<String>() val password = MutableLiveData<String>() [...] fun onRegister() { val userEmail = email. value. toString() val userPassword = password. value.
This class provides three static methods: map , switchMap and distinctUntilChanged which will be explained below.
LiveData is an observable data holder class. We can observe the data inside it and whenever the data change, observer will be notified and handle the data change. Unlike the other observable data holder, LiveData is lifecycle aware meaning that it's only observable to observer that was inside an active lifecycle state.
You can ignore my other answer. The solution is using MediatorLiveData<> in your view model. You add the LiveData from the repository as a data source to the MediatorLiveData<> and call setValue or postValue (depends on if it is in the UI tread or not) in the observer onChanged callback.
Like so
currentTransaction.addSource(application.getFinanceRepository().getTransaction(id),
new Observer<Transaction>() {
@Override
public void onChanged(@Nullable Transaction transaction) {
//Updates the MediatorLiveData<> that you activity is observing
currentTransaction.setValue(transaction);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With