How to handle Item clicks for a recycler view using RxJava

后端 未结 5 708
有刺的猬
有刺的猬 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:40

    My solution was much like @epool 's except use EventBus model.

    First, create a RxBus: RxBus.java

    public class RxBus {
        private final Subject _bus = new SerializedSubject<>(PublishSubject.create());
        public void send(Object o) { _bus.onNext(o); }
        public Observable toObserverable() { return _bus; }
        public boolean hasObservers() { return _bus.hasObservers(); }
    }
    
    
    

    Then, you have two way to use RxBus. Create your custom Application class with RxBus reference or create RxBus in Activity/Fragment then pass it to adapter. I'm use the first.

    MyApp.java

    public class MyApp extends Application {
        private static MyApp _instance;
        private RxBus _bus;
        public static MyApp get() {  return _instance; }
    
        @Override
        public void onCreate() {
            super.onCreate();
            _instance = this;
            _bus = new RxBus();
        }
    
        public RxBus bus() { return _bus; }
    }
    

    then use

    MyApp.get().bus() 
    

    to get RxBus instance.

    The usage of RxBus in Adpater was like this:

    public class MyRecyclerAdapter extends ... {
        private RxBus _bus;
    
        public MykRecyclerAdapter (...) {
            ....
            _bus = MyApp.get().bus();
        }
    
        public ViewHolder onCreateViewHolder (...) {
            _sub = RxView.longClicks(itemView)  // You can use setOnLongClickListener as the same
                  .subscribe(aVoid -> {
                            if (_bus.hasObservers()) { _bus.send(new SomeEvent(...)); }
                        });      
        }
    }
    

    You can send any class with _bus.send(), which We will recieve in the Activity:

    RxBus bus = MyApp.get().bus();  // get the same RxBus instance
    _sub = bus.toObserverable()
                .subscribe(e -> doSomething((SomeEvent) e));
    

    About unsubscribe.

    In MyRecyclerAdapter call _sub.unsubscribe() in clearup() methods and call _sub.unsubscribe() in Activity's onDestory().

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (_adapter != null) {
            _adapter.cleanup();
        }
        if (_sub != null) {
             _sub.unsubscribe()
        }
    }
    

    提交回复
    热议问题