Getting the index of an element from an Observable

2k views Asked by At

I'm beginning to learn RxJava. I have an array of Views that I want to set an OnClickListener to each of them using ViewObservable.clicks(). The implementation of the OnClickListener will just call a method that depends on the position of the view in the array (e.g.: populate(viewPositionInTheArray)).

An imperative solution will be this one:

for (int i = 0; i < views.length; i++) {
    final int finalI = i;
    view[i].setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            populate(finalI);
        }
    });
}

In order to do that using RxJava, I guess I'll need to do some stream chaining. However, I have no idea what functions I must use in an elegant, FRP way of doing it. Any suggestions?

Thanks

2

There are 2 answers

0
FriendlyMikhail On BEST ANSWER

Here's my stab at it. I ussualy use range operator when I need to maintain index through observable change

 Observable.range(0,views.length)
               .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                views[index].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        populate(index);
                    }
                });
            }
        });
0
Ivan Morgillo On

This could work:

private void gotTheList() {
    for (int i = 0; i < mViews.length; i++) {
        setClick(mViews[i], i);
    }
}

private void setClick(View item, int index) {
    ViewObservable.clicks(item)
            .subscribe(onClickEvent -> {
                populate(index);
            });
}

private void populate(int index) {
    // do something on mViews[index]
}