rx-java IO Scheduler 会维持顺序吗?

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

Does rx-java IO Scheduler maintains order?

问题

我想知道 `Schedulers.io()` 是否会按照调用者的顺序执行任务

```java
public class SaveTest {

    @Inject
    private MyRepository myRepository;

    public void save()  {
        Observable.range(0, 20)
                .map(l -> new MyModel(l))
                .observeOn(Schedulers.io())
                .subscribe(myRepository::save);
    }
}

在插入新数据时,即使不遵守顺序,也不会有问题。但是在更新时,例如:

    BankAccount account = new BankAccount();
    account.deposit(500);
    account.withdraw(50);

并且每个操作在反应流中保存,顺序非常重要。

我的问题是:IO 调度程序是否保持顺序?


<details>
<summary>英文:</summary>

I&#39;m wondering if the `Schedulers.io()` will execute tasks in the order of the caller.


```java
public class SaveTest {

    @Inject
    private MyRepository myRepository;

    public void save()  {
        Observable.range(0, 20)
                .map(l -&gt; new MyModel(l))
                .observeOn(Schedulers.io())
                .subscribe(myRepository::save);
    }
}

When inserting new data, even if the order is not respected there is no problem. But when updating ex :

    BankAccount account = new BankAccount();
    account.deposit(500);
    account.withdraw(50);

and each operation results in a save in a reactive stream the order is very important.

My question is : Does IO Scheduler maintains order ?

答案1

得分: 4

是的,响应式流会维护事件的顺序,即使您将事件交给不同的调度程序处理。

在内部,这些事件被放置在队列中,由调度程序选择的单线程工作器(如此处文档所述)按顺序从队列中获取它们。

英文:

Yes a reactive stream maintains the order of events, even if you hand off the events to a different scheduler like this.

Internally the events are put in a queue, and a single threaded worker selected by the scheduler (as documented here) picks them up from the queue, in order.

huangapple
  • 本文由 发表于 2020年4月9日 21:22:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/61122171.html
匿名

发表评论

匿名网友

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

确定