Khuzy Khuzy - 1 year ago 161
Android Question

Start with RxJava, loop

Can someone tell me how can I change default code of java like that:

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

for(Rates rates : ratesList)
rateItemArrayList.add(new RateItem(rates.getName(),rates.getCode(),rates.getValue()));

return rateItemArrayList;

to code in RxJava? Im just starting and i cant handle the basics yet : (

Answer Source

In RxJava you might do something like this, using the from and map functions.

private Observable<List<RateItem>> generateRates(List<Rates> ratesList) {
    Observable<List<RateItem>> myObservable = Observable.from(ratesList)
            .map(new Func1<List<Rates>, List<RateItem>>() {

                public List<RateItem> call(List<Rates> rateList) {
                    List<RateItem> items = new ArrayList<>();

                    for(Rates rates : ratesList) {
                        items.add(new RateItem(rates.getName(), rates.getCode(), rates.getValue()));
                    return items;

      return myObservable;

In this function, I am adding the ratesList object to be emitted by the observable. Then, as the list is being emitted, I map it to the List<RateItem> objects. Then I just return the Observable for subscription wherever I call this method.

If you are using RetroLamda, you could definitely make this look a little nicer (see @njzk2's comment) but I wanted to show what was actually going on.

As an example of how to subscribe to your new Observalbe, it would looks something like this:

    generateRates(new ArrayList<Rates>()).subscribe(new Func1<List<RateItem>>(){
        public void call(List<RateItem> rateItems) {
            // Do whatever it is you need to do with your list
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download