Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 217
Yura Buyaroff Avatar asked Mar 01 '16 21:03

Yura Buyaroff


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);


2 Answers

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 -> ...); 
like image 197
dwursteisen Avatar answered Sep 18 '22 06:09

dwursteisen


If you want to maintain the Lists emitted by the source Observable but convert the contents, i.e. Observable<List<SourceObject>> to Observable<List<ResultsObject>>, you can do something like this:

Observable<List<SourceObject>> source = ... source.flatMap(list ->         Observable.fromIterable(list)             .map(item -> new ResultsObject().convertFromSource(item))             .toList()             .toObservable() // Required for RxJava 2.x     )     .subscribe(resultsList -> ...); 

This ensures a couple of things:

  • The number of Lists emitted by the Observable is maintained. i.e. if the source emits 3 lists, there will be 3 transformed lists on the other end
  • Using Observable.fromIterable() will ensure the inner Observable terminates so that toList() can be used
like image 45
Noel Avatar answered Sep 18 '22 06:09

Noel