Observe data change from multiple table, using Room

Viewed 328

I have MutableLiveData of custom class named Data

private val mutableLiveData = MutableLiveData<Data>()

I have two table named A and B, first I get data from Table A and then from B. I do some business logic and then add it to mutableLiveData like below,

var obA = repository.getA()

var obB = repository.getB()

if (obA != null && obB != null) {
     mutableLiveData.postValue(Data(obA, obB))
}

Now I am observing this mutableLiveData in my one fragment, I want that any change in TableA or TableB shoul update mutableLiveData, which is not currently updating. I don't know is it possible or not? can anyone suggest me if it is possible then how can I achive this, thanks in advance.

1 Answers

Yes it is possible, here is java code based on what you posted. You can study google's basic sample for more insight. https://github.com/android/architecture-components-samples/tree/main/BasicSample

    MediatorLiveData<Data> mObservableAB = new MediatorLiveData<>();

    ObA obA = new ObA();


    ObB obB = new ObB();

    mObservableA.addSource(repository.getA(), new Observer<ObA>() {
        @Override
        public void onChanged(ObA obAx) {

             if(obAx != null)

                 obA = obAx;

                mObservableAB.postValue(new Data(obA, obB));

        }
    });

    mObservableB.addSource(repository.getB(), new Observer<ObB>() {
        @Override
        public void onChanged(ObB obBx) {

            if(obBx != null)

                obB=obBx;

                mObservableAB.postValue(new Data(obA, obB));

        }
    });

    
}

public LiveData<Data> getObservableAB(){

    return mObservableAB;   

}
Related