Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Item clicks for a recycler view using RxJava

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.

like image 256
J Whitfield Avatar asked Apr 08 '16 10:04

J Whitfield


1 Answers

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. */);
like image 170
epool Avatar answered Sep 23 '22 23:09

epool