RxJava2.0 Interval和IntervalRange操作符

689 阅读1分钟

Interval 操作符

先看一下 RxJava 的源码:

public static Observable<Long> interval(long initialDelay, long period, TimeUnit unit) {
    return interval(initialDelay, period, unit, Schedulers.computation());
}

public static Observable<Long> interval(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) {
    ObjectHelper.requireNonNull(unit, "unit is null");
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");
    return RxJavaPlugins.onAssembly(new ObservableInterval(Math.max(0L, initialDelay), Math.max(0L, period), unit, scheduler));
}

public static Observable<Long> interval(long period, TimeUnit unit) {
    return interval(period, period, unit, Schedulers.computation());
}

public static Observable<Long> interval(long period, TimeUnit unit, Scheduler scheduler) {
    return interval(period, period, unit, scheduler);
}

共有四个不同的重载方法,其中 1, 3, 4 都是直接调用了方法 2,所以直接看方法 2 就可以,periodunit 是所有方法都需要传的,initialDelayscheduler 可以自己设置,不传也会有默认值。

unit 是间隔时间的单位,TimeUnit 是一个枚举类型,直接调用需要使用的单位即可,如:TimeUnit.MINUTES 等。

period 就是定时任务的间隔时间,单位由 unit 来确认,这里只是指定数值。

initialDelay 就是需要延时多久才第一次执行,之后才会执行定时任务,不传的话默认和后边定时任务间隔时间相同。

scheduler 默认就是 Schedulers.computation(),也可以自己指定线程。

下边是每隔 100 毫秒执行一次定时任务的代码,其他的方法也是同理,按需传入参数即可。

Observable.interval(100, TimeUnit.MILLISECONDS)
    .subscribe(new Consumer<Long>() {
        @Override
        public void accept(Long aLong) throws Exception {
        
        }
});

IntervalRange 操作符

也先看一下 RxJava 的源码:

public static Observable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit) {
    return intervalRange(start, count, initialDelay, period, unit, Schedulers.computation());
}
public static Observable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, Scheduler scheduler) {
    if (count < 0) {
        throw new IllegalArgumentException("count >= 0 required but it was " + count);
    }

    if (count == 0L) {
        return Observable.<Long>empty().delay(initialDelay, unit, scheduler);
    }

    long end = start + (count - 1);
    if (start > 0 && end < 0) {
        throw new IllegalArgumentException("Overflow! start + count is bigger than Long.MAX_VALUE");
    }
    ObjectHelper.requireNonNull(unit, "unit is null");
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");

    return RxJavaPlugins.onAssembly(new ObservableIntervalRange(start, end, Math.max(0L, initialDelay), Math.max(0L, period), unit, scheduler));
}

共有两个不同的重载方法,period、unit、initialDelay 和 schedulerInterval 操作符中是一样的,只是多了 startcount 两个参数,来看一下这两个参数的意义即可。

start:从哪里开始,就是起始值。

count:要发送的数量。0 不发送 ,负数异常。

下边是从 1 开始输出 10 个数据,延迟 1 秒执行,每隔 2 秒执行一次的代码,输出结果为 1 到 10.

Observable.intervalRange(1, 10, 1, 2, TimeUnit.SECONDS)
    .subscribe(new Consumer<Long>() {
        @Override
        public void accept(Long aLong) throws Exception {
            Log.d(TAG, String.valueOf(aLong));
        }
});

IntervalRange 就是这样,按需传入参数即可。