How to handle Item clicks for a recycler view using RxJava

后端 未结 5 783
有刺的猬
有刺的猬 2021-02-01 21:49

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 ba

5条回答
  •  忘了有多久
    2021-02-01 22:51

    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 mViewClickSubject = PublishSubject.create();
    
    public Observable 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. */);
    

提交回复
热议问题