RxJava: How to convert List of objects to List of another objects

Yura Buyaroff picture Yura Buyaroff · Mar 1, 2016 · Viewed 60.2k times · Source

I have the List of SourceObjects and I need to convert it to the List of ResultObjects.

I can fetch one object to another using method of ResultObject:

convertFromSource(srcObj);

of course I can do it like this:

public void onNext(List<SourceObject> srcObjects) {
   List<ResultsObject> resObjects = new ArrayList<>();
   for (SourceObject srcObj : srcObjects) {
       resObjects.add(new ResultsObject().convertFromSource(srcObj));
   }
}

but I will be very appreciate to someone who can show how to do the same using rxJava.

Answer

dwursteisen picture dwursteisen · Mar 2, 2016

If your Observable emits a List, you can use these operators:

  • flatMapIterable (transform your list to an Observable of items)
  • map (transform your item to another item)
  • toList operators (transform a completed Observable to a Observable which emit a list of items from the completed Observable)

    Observable<SourceObjet> source = ...
    source.flatMapIterable(list -> list)
          .map(item -> new ResultsObject().convertFromSource(item))
          .toList()
          .subscribe(transformedList -> ...);