RxJava 将两个响应分组,其中一个响应可能为 NULL,带有 zip 运算符 [英] RxJava group two responses one of which might be NULL with zip operator

查看:67
本文介绍了RxJava 将两个响应分组,其中一个响应可能为 NULL,带有 zip 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 Realm 数据库发出两个并发请求并使用 RxJava 返回结果.问题是其中一个请求可以返回 NULL 对象并且我崩溃了.即使其中一个为 NULL,如何从两个数据库正确返回结果?谢谢.

I want to make two concurent request to Realm database and return results with RxJava. The issue is that one of requests can return NULL object and I have a crash. How can I properly return results from both DB even if one of them NULL? Thanks.

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)

推荐答案

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

You can return Optional from DB and then check if it's present.

这篇关于RxJava 将两个响应分组,其中一个响应可能为 NULL,带有 zip 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆