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.
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. */);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With