RxJava组的两个响应中的一个可能是带有zip运算符的NULL

时间:2018-05-14 15:52:35

标签: java android realm rx-java rx-java2

我想向Realm数据库发出两个concurent请求并使用RxJava返回结果。问题是其中一个请求可以返回NULL对象,我遇到了崩溃。如果其中一个是NULL,我怎样才能正确返回两个DB的结果?感谢。

public void getDataFromTwoSources(DisposableObserver<ComplexUserDto> observer, String shopId) {
        Preconditions.checkNotNull(observer);

        final Observable<ComplexUserDto> observable = Observable.zip(firstRepository.getUserData(userId), secondRepository.getUserDetailData(userId),
                (userData, userDetails) -> {
                    ComplexUserDto resultDto = new ComplexUserDto(userData, userDetails);
                    return resultDto;
                })
                .compose(rxTransformers.applyUnauthorizedHandler())
                .compose(rxTransformers.applySchedulers());
        addDisposable(observable.subscribeWith(observer));
    }

public class ComplexUserDto {
    private UserData userData;
    private UserDetailData userDetailData;

    public ComplexUserDto(UserData userData, UserDetailData userDetailData) {
        this.userData = userData;
        this.userDetailData = userDetailData;
    }

    public UserData getUserData() {
        return userData;
    }

    public UserDetailData getUserDetailData() {
        return userDetailData;
    }
}

例外:

java.lang.NullPointerException: onNext called with null. Null values are generally not allowed in 2.x operators and sources.
        at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:63)
        at com.yozhik.data.database.shop.RealmDatabaseManagerImpl.lambda$null$15$RealmDatabaseManagerImpl(RealmDatabaseManagerImpl.java:261)
        at com.yozhik.data.database.shop.RealmDatabaseManagerImpl$$Lambda$15.execute(Unknown Source)
        at io.realm.Realm$1.run(Realm.java:1502)
        at io.realm.internal.async.BgPriorityRunnable.run(BgPriorityRunnable.java:34)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:0)

您可以从DB返回Optional,然后检查它是否存在。