RxJava在项目中的特殊使用场景

本文基于:RaJava 2.1.14,另外本文不会对操作符的使用进行介绍,详情请参考RxJava 2.x Operators

参考:

轮播

根据需要改变本次延迟订阅时间

repeat将会在每次请求回调Observer.onComplete()或者Subscriber.onComplete()之前就会重新订阅事件,而repeatWhen可以根据自己的需求确定是否需要再次进行循环、延迟订阅、改变延迟订阅时间等。这就比较符合在我项目中的需求:第一次请求完成之后需要延迟一分钟再订阅,如果未打断请求的话将会改变这个订阅时间为两分钟。本来采用repeatWhen + delay能够实现固定的轮播的效果,但却不能动态的改变轮播的间隔,于是改为repeatWhen + flatMap + timer来实现:

Observable.just(2)
                .repeatWhen(objectObservable -> objectObservable
                        .flatMap((Function<Object, ObservableSource<?>>) o -> Observable.timer(getRepeatInterval(), TimeUnit.SECONDS)))
                .subscribeWith(new DebugResourceObserver<>());

getRepeatInterval()可以动态的返回你设置的时间

打断轮播

使用上述方式可以动态改变每次重订阅的时间,现在我们还需要加入条件来打断轮播。使用filter操作符就可以实现轮播的打断操作。

Observable.just(2)
                .repeatWhen(objectObservable -> objectObservable
                        .filter(o -> abort())
                        .flatMap((Function<Object, ObservableSource<?>>) o -> Observable.timer(getRepeatInterval(), TimeUnit.SECONDS)))
                .subscribeWith(new DebugResourceObserver<>());

intervalRange

intervalRange操作符来实现,定义如下:

Signals a range of long values, the first after some initial delay and the rest periodically after.
<p>
The sequence completes immediately after the last value (start + count - 1) has been reached.
<p>
@param start that start value of the range
@param count the number of values to emit in total, if zero, the operator emits an onComplete after the initial delay
@param initialDelay the initial delay before signalling the first value (the start)
@param period the period between subsequent values
@param unit the unit of measure of the initialDelay and period amounts
@return the new Observable instance

具体使用:

Observable.just(2)
                .repeatWhen(new Function<Observable<Object>, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Observable<Object> objectObservable) throws Exception {
                        return objectObservable
                                .filter(o -> abort())
                                .flatMap((Function<Object, ObservableSource<?>>) o -> Observable.intervalRange(0, getCount(), 0, getRepeatInterval(), TimeUnit.SECONDS));
                    }
                });

暂时涉及到自己的一些“需求”就这些!希望对大家有帮助!

猜你喜欢

转载自www.cnblogs.com/yangshanlin/p/9207107.html