如何观察java rx中的调用线程?

tiq*_*iqz 7 android-syncadapter rx-java rx-android

无论如何要告诉java rx使用observeOn函数中的当前线程?我正在为android syncadapter编写代码,我希望在同步适配器线程中观察结果,而不是在主线程中.

使用Retrofit + RX Java的示例网络调用看起来像这样:

MyRetrofitApi.getInstance().getObjects()
.subscribeOn(Schedulers.io())
.observeOn(<current_thread>)
.subscribe(new Subscriber<Object>() {
    //do stuff on the sync adapter thread

}
Run Code Online (Sandbox Code Playgroud)

我尝试过使用

...
.observeOn(AndroidSchedulers.handlerThread(new Handler(Looper.myLooper())))
...
Run Code Online (Sandbox Code Playgroud)

这是相同的方式安卓RX创建主线程调度程序,但只要我代替不工作Looper.myLooper()Looper.getMainLooper().

我可以使用Schedulers.newThread(),但作为其复杂的同步代码与许多服务器调用我将不断创建一个新的线程,只是为了触发新的网络调用,再次创建新的线程,以启动更多的网络调用.有没有办法做到这一点?或者我的方法本身是完全错误的?

dav*_*ola 1

哦,我刚刚在 wiki 中找到了这个:https://github.com/ReactiveX/RxAndroid#observing-on- Arbitration-threads

new Thread(new Runnable() {
    @Override
    public void run() {
        final Handler handler = new Handler(); // bound to this thread
        Observable.just("one", "two", "three", "four", "five")
                .subscribeOn(Schedulers.newThread())
                .observeOn(HandlerScheduler.from(handler))
                .subscribe(/* an Observer */)

        // perform work, ...
    }
}, "custom-thread-1").start();
Run Code Online (Sandbox Code Playgroud)

我认为这也应该适用于你的情况 - 当然,除了创建一个新线程......所以只是:

final Handler handler = new Handler(); // bound to this thread
MyRetrofitApi.getInstance().getObjects()
    .subscribeOn(Schedulers.io())
    .observeOn(HandlerScheduler.from(handler))
    .subscribe(new Subscriber<Object>() {
        //do stuff on the sync adapter thread

    }
Run Code Online (Sandbox Code Playgroud)