RxJava,为什么1和2在这个序列中不按顺序到达?

huangapple go评论63阅读模式
英文:

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 -&gt; {
          if (a &lt; 3) {
            return Observable.just(a).delay(3, TimeUnit.SECONDS);
          } else {
            return Observable.just(a);
          }
        })
    .doOnNext(
        a -&gt; System.out.println(&quot;Element: &quot; + 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 不会等待最后一个项目完全处理完毕,所以对于 12,它们会在不同的线程(从计算池中获取)中并行处理。不同的线程意味着没有顺序保证

所有基于时间的操作符默认都使用计算调度器。您可以在这里查看我的其他答案链接

英文:

By default delay operator uses computation scheduler :

    @CheckReturnValue
    @SchedulerSupport(SchedulerSupport.COMPUTATION)
    public final Observable&lt;T&gt; 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

huangapple
  • 本文由 发表于 2020年9月24日 08:52:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64038105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定