因此,刚接触RX Java的人有一个问题。
在我学习作为RXJava的野兽的探险中,这是我受测的课程。
public class PollingLoop {
public static <T> Observable<T> buildObservable(
final int interval,
final TimeUnit timeUnit,
final int maxJitter,
final Scheduler scheduler,
final Supplier<Observable<T>> scheduledTask) {
if (maxJitter <= 0) throw new IllegalArgumentException("Jitter must be greater than 0");
final Random randomJitter = new Random();
return Observable.timer(interval, timeUnit, scheduler)
.map(x -> {
System.out.println("Flat map jitter");
return randomJitter.nextInt(maxJitter);
})
.flatMap(jitter -> {
System.out.println("Flat map timer");
return Observable.timer(jitter, timeUnit, scheduler);
})
.flatMap(ignored -> {
System.out.println("Flat map task");
return scheduledTask.get();
})
.retry()
.repeat();
}
public static <T> Completable buildCompletable(
final int interval,
final TimeUnit timeUnit,
final int maxJitter,
final Scheduler scheduler,
final Supplier<Completable> scheduledTask) {
if (maxJitter <= 0) throw new IllegalArgumentException("Jitter must be greater than 0");
final Random randomJitter = new Random();
return Observable.timer(interval, timeUnit, scheduler)
.map(x -> {
System.out.println("Flat map jitter");
return randomJitter.nextInt(maxJitter);
})
.flatMapCompletable(jitter -> {
System.out.println("Flat map timer");
return Completable.timer(jitter, timeUnit, scheduler);
})
.flatMapCompletable(ignored -> {
System.out.println("Flat map task that is not called");
return scheduledTask.get();
})
.retry()
.repeat()
.toCompletable();
}
}
从测试中,当我测试Observable的执行延迟时,得到输出
Flat map jitter
Flat map timer
Flat map task //(observable is being called)
我究竟做错了什么?为什么未从buildCompletable内部调用Completable任务?
德玛西亚99
相关分类