英文:
RxJava, why 1 and 2 don't arrive in order in this sequence?
问题
Observable.just(1, 2, 3, 4, 5)
.flatMap(
a -> {
if (a < 3) {
return Observable.just(a).delay(3, TimeUnit.SECONDS);
} else {
return Observable.just(a);
}
})
.doOnNext(
a -> System.out.println("Element: " + a )
.subscribe();
如果1和2等待3秒钟,为什么有时候会先出现2,然后是1?难道不应该始终先出现1吗?
有时候的输出:
Element: 3
Element: 4
Element: 5
Element: 2
Element: 1
以及
Element: 3
Element: 4
Element: 5
Element: 1
Element: 2
难道不应该始终按照这种顺序输出(3, 4, 5, 1, 2)吗?
英文:
Observable.just(1, 2, 3, 4, 5)
.flatMap(
a -> {
if (a < 3) {
return Observable.just(a).delay(3, TimeUnit.SECONDS);
} else {
return Observable.just(a);
}
})
.doOnNext(
a -> System.out.println("Element: " + a )
.subscribe();
If 1 and 2 wait 3 seconds, why sometimes 2 comes first and then 1? Shouldn't it always be 1 first?
sometimes:
Element: 3
Element: 4
Element: 5
Element: 2
Element: 1
and
Element: 3
Element: 4
Element: 5
Element: 1
Element: 2
shouldn't it always go out like this (3,4,5,1,2)?
答案1
得分: 1
默认情况下,delay
操作符使用计算调度器:
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Observable<T> delay(long delay, TimeUnit unit) {
return delay(delay, unit, Schedulers.computation(), false);
}
这意味着每个延迟操作都在从计算池中获取的线程中执行。
flatMap
不会等待最后一个项目完全处理完毕,所以对于 1
和 2
,它们会在不同的线程(从计算池中获取)中并行处理。不同的线程意味着没有顺序保证。
所有基于时间的操作符默认都使用计算调度器。您可以在这里查看我的其他答案链接。
英文:
By default delay
operator uses computation scheduler :
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Observable<T> delay(long delay, TimeUnit unit) {
return delay(delay, unit, Schedulers.computation(), false);
}
That means each delay operation is executed in a thread that is taken from computation pool.
flatMap
do not wait the last item was completely processed, So for 1
and 2
they are processed in different threads (taken from computation pool) in parallel. Different threads means no order guaranteed.
All time based operators use computation scheduler by default. You can take a look to my other answer here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论