以下示例详细解释了我的用例
假设你有一个用户类
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后启动.
这意味着我希望在andThen运算符启动时初始化mUser.
以下是我对此观察的订阅
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,然后在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.
解决方法
这里的问题是,在尝试使用just创建Observable时,mUser为null.
解决方案:您需要推迟创建String Observable直到订阅发生,直到然后上游开始发布.
而不是andThen(Observable.just(mUser.name));
使用
andThen(Observable.defer(() -> Observable.just(mUser.name)));
要么
andThen(Observable.fromCallable(() -> mUser.name));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。