rx-android (or rx-java) with refreshlayout



我使用swiperefreshlayout android.support.v4.widget.SwipeRefreshLayout,并使用rxjava在每次滑动发生时查询服务器。我的代码如下所示,我必须在OnRefreshListener中创建重复的可观察对象和订阅者,以便调用它们,由于代码重复,这看起来非常糟糕。如果我使用原始的(在外部声明的),则永远不会返回订阅者(没有触发onNextonErroronCompleted)。在这种情况下,RxJava遗漏了什么?

Subscriber<ListVerifyResponseWrapper> subscriber = new Subscriber<ListVerifyResponseWrapper>() {
            @Override
            public void onCompleted() {
                LogUtils.LOGD(TAG, "completed");
            }
            @Override
            public void onError(Throwable e) {
                Toast.makeText(getActivity(), getString(R.string.An_error_has_occured), Toast.LENGTH_SHORT).show();
                mSwipeRefreshLayout.setRefreshing(false);
            }
            @Override
            public void onNext(ListVerifyResponseWrapper listVerifyResponseWrapper) {
                changeViewStateAccordingToResult(listVerifyResponseWrapper);
            }
        };

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Observable<ListVerifyResponseWrapper> observableDuplicate = RestClient.getInstance().getRestApi().getListVerifyRequestDetail(model);
                final Subscriber<ListVerifyResponseWrapper> subscriberDuplicate = new Subscriber<ListVerifyResponseWrapper>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.LOGD(TAG, "completed");
                    }
                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getActivity(), getString(R.string.An_error_has_occured), Toast.LENGTH_SHORT).show();
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                    @Override
                    public void onNext(ListVerifyResponseWrapper listVerifyResponseWrapper) {
                        changeViewStateAccordingToResult(listVerifyResponseWrapper);
                    }
                };
                observableDuplicate.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.newThread()).subscribe(subscriberDuplicate);
            }
        });
        observable.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.newThread()).subscribe(subscriber);

谢谢

我遇到了完全相同的问题。我通过链接

解决了这个问题
.observeOn(AndroidSchedulers.mainThread())

在最终订阅者之前。显然,你必须确保UI相关的东西在UI线程

上完成

在Johnnycube的答案(正确)之上,我建议您使用

subscribeOn(Schedulers.io())

是用来处理回调的

相关内容

  • 没有找到相关文章

最新更新