Yura Buyaroff Yura Buyaroff - 5 months ago 86x
Android Question

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:


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.


The Observable.from() factory method allows you to convert a collection of objects into an Observable stream. Once you have a stream you can use the map operator to transform each emitted item. Finally, you will have to subscribe to the resulting Observable in order to use the transformed items:

// Assuming List<SourceObject> srcObjects
Observable<ResultsObject> resultsObjectObservable = Observable.from(srcObjects).map(new Func1<SourceObject, ResultsObject>() {
    public ResultsObject call(SourceObject integer) {
        return new ResultsObject().convertFromSource(srcObj);

resultsObjectObservable.subscribe(new Action1<ResultsObject>() { // at this point is where the transformation will start
    public void call(ResultsObject resultsObject) { // this method will be called after each item has been transformed
        // use each transformed item