问题描述
我有一个用例,其中我在Completable中初始化一些全局变量,然后在链的下一步(使用 andThen
运算符)中使用这些变量.
以下示例详细说明了我的用例
假设您有一个类 User
类User {字符串名称;}
我有一个这样的Observable,
私有用户mUser;//这是一个全局变量公共Observable< String>stringObservable(){返回Completable.fromAction(()-> {mUser = new User();mUser.name =名称";}).then(Observable.just(mUser.name));}
首先,我要在 Completable.fromAction
中进行一些初始化,并且我希望 andThen
运算符仅在完成 Completable.fromAction
之后才能启动
这意味着我希望 andThen
运算符启动时会初始化 mUser
.
以下是我对此观察性的订阅
stringObservable().subscribe(s-> Log.d(TAG,"success:" + s),投掷->Log.e(TAG,"error:" + throwable.getMessage()));
但是当我运行此代码时,出现错误
尝试从空对象引用中的字段'java.lang.String User.name'中读取
这意味着 mUser
为null,然后Then
在执行 Completable.fromAction
中的代码之前启动.这里发生了什么事?
根据 andThen
问题不在于 andThen
,而是内部的语句 Observable.just(mUser.name)
andThen
.尽管 just
运算符仅在 Completable.fromAction
之后才会发出,但它会尝试立即创建可观察对象.
这里的问题是,尝试使用just创建 Observable
时, mUser
为空.
解决方案:您需要推迟String Observable的创建,直到发生订阅为止,直到 andThen
的上游开始发出.
而不是 andThen(Observable.just(mUser.name));
使用
andThen(Observable.defer(()-> Observable.just(mUser.name)));
或
andThen(Observable.fromCallable(()-> mUser.name));
I have a usecase where I initiallize some global variables in a Completable , and in the next step in the chain (using andThen
operator) I make use of those variables.
Following sample explains my usecase in detail
Say you have a class User
class User {
String name;
}
and I have an Observable like this ,
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));
}
First I'm doing some initiallizations in my Completable.fromAction
and I expect andThen
operator to start only after completing the Completable.fromAction
.
Which means I expect mUser
to be initallized when the andThen
operator starts.
Following is my subscription to this observable
stringObservable()
.subscribe(s -> Log.d(TAG, "success: " + s),
throwable -> Log.e(TAG, "error: " + throwable.getMessage()));
But when I run this code , I get an error
Attempt to read from field 'java.lang.String User.name' on a null object reference
which means mUser
is null , andThen
started before executing the code in Completable.fromAction
. Whats happening here?
According to documentation of andThen
The issue is not with andThen
but with the statement Observable.just(mUser.name)
inside andThen
. The just
operator will try to create the observable immediately though it will emit only after Completable.fromAction
.
Problem here is , while trying to create the Observable
using just , the mUser
is null.
Solution : You need to defer the creation of the String Observable till a subscription happens , till the upstream of andThen
starts emission.
Instead of andThen(Observable.just(mUser.name));
use
andThen(Observable.defer(() -> Observable.just(mUser.name)));
Or
andThen(Observable.fromCallable(() -> mUser.name));
这篇关于RxJava的`Completable.andThen`没有串行执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!