How to handle Item clicks for a recycler view using RxJava

J Whitfield picture J Whitfield · Apr 8, 2016 · Viewed 8.5k times · Source

I was interested to find out what is the best way to respond to a item click of a recycler view.

Normally I would add a onclick() listener to the ViewHolder and pass back results to the activity/fragment through a interface.

I thought about adding a Observable in the onBindViewHolder but i do not want to create a new Observable for every item binding.

Answer

epool picture epool · Oct 10, 2016

You can use RxBinding and then create a subject inside of your adapter, then redirect all the events to that subject and just create a getter of the subject to act as an observable and finally just subscribe you on that observable.

private PublishSubject<View> mViewClickSubject = PublishSubject.create();

public Observable<View> getViewClickedObservable() {
    return mViewClickSubject.asObservable();
}

@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup pParent, int pViewType) {
    Context context = pParent.getContext();
    View view = (View) LayoutInflater.from(context).inflate(R.layout.your_item_layout, pParent, false);
    ViewHolder viewHolder = new ViewHolder(view);

    RxView.clicks(view)
            .takeUntil(RxView.detaches(pParent))
            .map(aVoid -> view)
            .subscribe(mViewClickSubject);

    return viewHolder;
}

An usage example could be:

mMyAdapter.getViewClickedObservable()
        .subscribe(view -> /* do the action. */);