Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJava 2 Flowable`s mergeWith not merging

I have this method on my Room`s dao

@Query("SELECT * FROM Expense WHERE date >= :initDate AND date <= :endDate AND chargeableUuid = :chargeableUuid ORDER BY date")
fun currentMonth(initDate: Long, endDate: Long, chargeableUuid: String): Flowable<List<Expense>>

and I am using it this way:

dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
            .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
            .subscribe { Log.i("test", "size ${it.size}" }

If I execute each call separately both return one element each (different elements), but when I execute them together the log outputs that just one element is in the returned list.

How can I merge the emitions from two Flowables into one?

like image 520
jonathanrz Avatar asked Mar 07 '23 09:03

jonathanrz


1 Answers

When you use the merge (or mergeWith) operator as you can see in the diagram, you will have an Observable that emits all the items emitted from all the Observable (or Flowable you are merging).

enter image description here

So, actually your subscriber will receive two List. If you want just one Flowable that emit one single item (a list) containing all the items contained in all the lists, you can use the toList operator:

doing

dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
            .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
    .toList()

you'll create a Flowable that emits a list of list, List<List< Expense>> that will contains your two lists. So you can map it in a single list:

dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
   .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
    .toList()
    .map(lists -> {
     List<Expense> l = new ArrayList<>();
     for (List<Expense> list : lists) {
          l.addAll(list);
     }
     return l;
})

If you subscribe now, you will get a single list containing two Expense objects.

like image 70
GVillani82 Avatar answered Mar 24 '23 08:03

GVillani82