简体   繁体   English

RxJava线程安全

[英]RxJava thread-safety

Is this code thread-safe? 这段代码是线程安全的吗?

Observable<String> observable = ... // some observable that calls
                                    // onNext from a background thread

observable
  .scan(new ArrayList<String>(), (List<String> acc, String next) -> {
    acc.add(next);
    return acc;
  })
  .subscribe( list -> {
    // do somethind with sequence of lists
    ...
  });

I'm curious because ArrayList is not a thread-safe data structure. 我很好奇,因为ArrayList不是一个线程安全的数据结构。

As a quick answer, in .NET (the original Rx implementation) all values from an observable sequence can be assumed to be sequential. 作为一个快速回答,在.NET(原始Rx实现)中,可以假定来自可观察序列的所有值都是顺序的。 This does not preclude it to be multi-threaded. 这并不排除它是多线程的。 However if you are producing values in a multi-threaded manner, then you may want enforce the sequential nature by looking for the equivalent function to the .NET Synchronize() Rx operator. 但是,如果以多线程方式生成值,则可能需要通过查找.NET Synchronize() Rx运算符的等效函数来强制执行顺序性。

Another option is to check the implementation of Scan in the RxJava source code, to validate that it does enforce the sequential nature you would want/expect to provide you safety in your accumulator function. 另一种选择是在RxJava源代码中检查Scan的实现,以验证它是否确实强制执行您希望/期望为累加器函数提供安全性的顺序性。

如果此代码不是线程安全的,则RxJava被破坏或您的Observable源被破坏 - 不可重入的运算符是Rx契约的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM