I have a super class called Transaction {} and have two other classes that extend it called
InTransaction and OutTransaction.
InTransaction links to another Room entity called Source and OutTransaction links to another entity called Category.
I am able to individually observe each type's model, which returns PagedList<? extends Transaction>
.
In my PagedListAdapter, I'd like to show both types of items. But my implementation of MediatorLiveData does not seem to work correctly. It seems the recent type replaces the old type and as a result, only one type of transaction is displayed.
I'd like to be able to see all types of transactions. Below is my current code.
transactionLiveData = new MediatorLiveData<>();
transactionLiveData.addSource(inTransactionViewModel.getItems(), transactionLiveData::setValue);
transactionLiveData.addSource(outTransactionViewModel.getItems(), transactionLiveData::setValue);
transactionLiveData.observe(requireActivity(), transactionAdapter::submitList);
I do understand that MediatorLiveData does not do the merging for you rather simply notifies you of changes.
How can I merge the two PagedList
into one then submit to the list?
I'm thinking of doing something like this but not sure how to instantiate the aggregator PagedList
class TransactionMerger extends MediatorLiveData<PagedList<? extends Transaction>> {
PagedList<? extends Transaction> inTransactions;
PagedList<? extends Transaction> outTransactions;
PagedList<? extends Transaction> aggregator;
TransactionMerger(){
}
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super PagedList<? extends Transaction>> observer) {
super.observe(owner, observer);
}
@Override
public void setValue(PagedList<? extends Transaction> value) {
if (isInTransactionList(value)) {
inTransactions = value;
}else{
outTransactions = value;
}
// TODO Merge the two
aggregator = mergeLists(inTransactions, outTransactions);
super.setValue(aggregator );
}
private boolean isInTransactionList(PagedList<? extends Transaction> list) {
return list != null && list.size() > 0 && list.get(0).getTransactionType() == Transaction.TransactionType.In;
}
}
Thanks