本文介绍了Schedulers.io()不返回主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RxParse解析查询的异步负载,但是当我使用subscriptionOn(Schedulers.io())订阅我的可观察对象时,永远不会在主线程上调用onCompleted方法.取而代之的是,在工作线程池内部调用了我的onCompleted方法.如果我使用observeOn(AndroidSchedulers.mainThread),那么一切都会正常运行,但是我的onNextMethod也将在主线程上调用,而我不希望这样做.

I'm using RxParse to parse query's async load but when i subscribe my observable using subscribeOn(Schedulers.io()) my onCompleted method is never called on main thread. Instead of this, my onCompleted method is called inside of worker thread pool. If i use observeOn(AndroidSchedulers.mainThread) everything will work as well, but my onNextMethod will be called on main thread too and I don't want it.

我的代码有问题吗?

我的代码有什么问题吗?

Have anything wrong in my code?

ParseObservable.find(myQuery)
    .map(myMapFunc())
    .subscribeOn(AndroidSchedulers.handlerThread(new Handler()))
    .subscribe(
        new Subscriber<MyObj>() {
           @Override
            public void onError(Throwable e) {
                Log.e("error","error",e);
            }

            @Override
            public void onNext(T t) {
                // ... worker thread (but here is ok)
            }

            public void onCompleted() {
                // ... worker thread again instead of mainThread
            }
        }
    )
);

推荐答案

不幸的是,所有方法(onNextonErroronCompleted

Unfortunately the subscription is in the same thread for all methods (onNext, onError and onCompleted

但是您可以在Schedulers.io()onNext(T t)方法内部进行观察,创建一个新的Observable来监听MainThread,如下所示:

But you can observe in the Schedulers.io() and inside the onNext(T t) method, create a new Observable to listen in the MainThread like this:

ParseObservable.find(myQuery)
    .map(myMapFunc())
    .subscribeOn(Schedulers.io())
    .subscribe(
        new Subscriber<MyObj>() {
           @Override
            public void onError(Throwable e) {
                Log.e("error","error",e);
            }

            @Override
            public void onNext(T t) {
                Observable.just(t)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((t) -> {
                         // do something in MainThread
                    })
            }

            public void onCompleted() {
                // ... worker thread again instead of mainThread
            }
        }
    )
);

希望对您有帮助!

这篇关于Schedulers.io()不返回主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 10:15