Khuzy Khuzy - 1 year ago 56
Android Question

RxJava explain this loop

can someone explain me this loop?

private Observable<ArrayList<RateItem>> generateRates(List<Rates> rates){
rateItemArrayList = new ArrayList<RateItem>();

Observable<ArrayList<RateItem>> observable = Observable.from(rates)
.map(new Func1<Rates, ArrayList<RateItem>>() {
public ArrayList<RateItem> call(Rates r) {
for(Rates rat : rates)
rateItemArrayList.add(new RateItem(rat.getName(),rat.getCode(),rat.getValue()));
return rateItemArrayList;
return observable;

My List has 35(checked) items after response from server, then i want to make different ArrayList from this list. Why this loop iterate about 1000 times instead of 35? After that my new ArrayList has 1350 items o.O.

Answer Source

you code contains a side effect : a method update a object outside of his context (here, the map method update a list outside of it).

Then your for loop is quite strange as you loop over rates variables, which is used to build the Observable too. (Which I think is not expected)

Your code can be simplier, using non side effect code :

 private Observable<List<RateItem>> generateRates(List<Rates> rates){
      return Observable.from(rates)
                       .map(r -> new RateItem(r.getName(), r.getValue())

it should be quite close to what you want to achieve.