如何将Retrofit 2与Realm和RxJava结合起来

时间:2016-03-09 16:53:17

标签: multithreading realm rx-java retrofit2

我想在后台线程上保存对领域的改进响应然后将其传递给UI线程,但它有点棘手,因为Realm对线程非常敏感。所以代码看起来像这样,请提交您所有更好的解决方案:)

restApi.userRealmList()
        .doOnNext(userRealmModels -> {
            if (userRealmModels != null){
                mRealm = Realm.getInstance(mContext);
                mRealm.asObservable()
                        .map(realm -> mRealm.copyToRealmOrUpdate(userEntity))
                        .subscribe(new Subscriber<Object>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(Object o) {
                                Log.d("RealmManager", "user added!");
                            }
                        });
            }})
        .map(userEntityDataMapper::transformAll)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<User>>() {
             @Override
             public void onCompleted() {
                 hideViewLoading();
             }

             @Override
             public void onError(Throwable e) {
                 hideViewLoading();
                 showErrorMessage(new DefaultErrorBundle((Exception) e));
                 showViewRetry();
             }

             @Override
             public void onNext(List<User> users) {
                 showUsersCollectionInView(users);
             }
        });

1 个答案:

答案 0 :(得分:4)

您的代码看起来不能编译吗?例如。什么是userEntity。你的copyToRealmOrUpdate也不在事务中,因此也会崩溃,但它与线程无关。

如果您想将某些数据作为副作用保存,然后再将其发送到用户界面,您应该可以执行以下操作:

restApi.userRealmList()
        .doOnNext(userRealmModels -> {
            if (userRealmModels != null) {
                Realm realm = Realm.getInstance(mContext);
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(userRealmModels);
                realm.commitTransaction();
                realm.close();
            }})
        .map(userEntityDataMapper::transformAll)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<User>>() {
             @Override
             public void onCompleted() {
                 hideViewLoading();
             }

             @Override
             public void onError(Throwable e) {
                 hideViewLoading();
                 showErrorMessage(new DefaultErrorBundle((Exception) e));
                 showViewRetry();
             }

             @Override
             public void onNext(List<User> users) {
                 showUsersCollectionInView(users);
             }
        });