我有一个用例,我在 Completable 中初始化了一些全局变量,并在链的下一步中(使用 andThen
运算符)我使用了这些变量。
以下示例详细解释了我的用例
假设你有一个类 User
class User {
String name;
}
我有一个像这样的 Observable,
private User mUser; // this is a global variable
public Observable<String> stringObservable() {
return Completable.fromAction(() -> {
mUser = new User();
mUser.name = "Name";
}).andThen(Observable.just(mUser.name));
}
首先,我在我的 Completable.fromAction
中进行一些初始化,我希望 andThen
运算符仅在完成 Completable.fromAction
后才开始.
这意味着我希望 mUser
在 andThen
运算符启动时被初始化。
以下是我对这个observable的订阅
stringObservable()
.subscribe(s -> Log.d(TAG, "success: " + s),
throwable -> Log.e(TAG, "error: " + throwable.getMessage()));
但是当我运行这段代码时,我得到一个错误
Attempt to read from field 'java.lang.String User.name' on a null object reference
这意味着 mUser
为 null , andThen
在执行 Completable.fromAction
中的代码之前开始。这里发生了什么事?
根据andThen
的文档
Returns an Observable which will subscribe to this Completable and once that is completed then will subscribe to the {@code next} ObservableSource. An error event from this Completable will be propagated to the downstream subscriber and will result in skipping the subscription of the Observable.
最佳答案
问题不在于 andThen
而在于 andThen
中的语句 Observable.just(mUser.name)
。 just
运算符将尝试立即创建可观察对象,尽管它只会在 Completable.fromAction
之后发出。
这里的问题是,在尝试仅使用 创建 Observable
时,mUser
为空。
解决方案:您需要将 String Observable 的创建推迟到订阅发生,直到 andThen
的上游开始发射。
代替 andThen(Observable.just(mUser.name));
使用
andThen(Observable.defer(() -> Observable.just(mUser.name)));
或者
andThen(Observable.fromCallable(() -> mUser.name));
关于java - RxJava `Completable.andThen` 不是串行执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48624863/