Android轮询器,RxJava Interval;

基于RxJava实现轮询器,配合Retrofit处理网络请求轮询很好用,其它的一些轮询也都可以使用像Bannre图之类的;

implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
 private Disposable subscribe;
      //开始轮询
    public void start(View view) {
        //interval对应参数 :首次执行延时时间 、 每次轮询间隔时间 、 时间类型
        subscribe = Observable.interval(0,1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        Log.i("ccb", "accept: " + aLong);
                    }
                });
        // 有限制次数的轮询器
//        Observable.intervalRange(0,10,0,1,TimeUnit.SECONDS)
//                .subscribe(new Consumer<Long>() {
//                    @Override
//                    public void accept(Long aLong) throws Exception {
//                        Log.i("ccb", "accept: "+aLong);
//                    }
//                });
    }
       //结束轮询
    public void shop(View view) {
        //停止轮询,销毁这个Subscribe;
        if (!subscribe.isDisposed())  subscribe.dispose();
    }

如图,在轮询到第10次时结束了轮询;

猜你喜欢

转载自blog.csdn.net/qq_35605213/article/details/82760836