3

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

TheRealChx101
  • 1,468
  • 21
  • 38
  • 2
    I don't think it's possible to merge PagedLists. You're probably going to have a better chance at merging RecyclerView.Adapters using the new `MergeAdapter`. – EpicPandaForce May 30 '20 at 10:05
  • 1
    MergeAdapter looks really awesome. It's working ok so far. However, is it possible to order all the items by a specific field (In this case, Date timestamp, newest first). This means mixing all the items, and not just showing Adapter items first – TheRealChx101 May 30 '20 at 13:44

0 Answers0