How to handle Item clicks for a recycler view using RxJava

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

    I would suggest you to do with your initial aproach of an observable per element on click, but in order to avoid create a new observable every time you can just cache the items emitted the first time using cache.

          /**
     * Here we can prove how the first time the items are delayed 100 ms per item emitted but second time becuase it´s cached we dont have any delay since 
     * the item emitted are cached
     */
    @Test
    public void cacheObservable() {
        Integer[] numbers = {0, 1, 2, 3, 4, 5};
    
        Observable observable = Observable.from(numbers)
                                                   .doOnNext(number -> {
                                                       try {
                                                           Thread.sleep(100);
                                                       } catch (InterruptedException e) {
                                                           e.printStackTrace();
                                                       }
                                                   })
                                                   .cache();
        long time = System.currentTimeMillis();
        observable.subscribe(System.out::println);
        System.out.println("First time took:" + (System.currentTimeMillis() - time));
        time = System.currentTimeMillis();
        observable.subscribe(System.out::println);
        System.out.println("Second time took:" + (System.currentTimeMillis() - time));
    
    }
    

提交回复
热议问题