RxJava在服务线程上订阅

Bry*_*yan 0 android android-service rx-java rx-android

我创建了一个简单IntentService的文件和一些数据上传到服务器。我希望能够Toast在上传完成时显示,但是我需要在主线程上才能执行此操作。

由于我将RetroFit与RxJava结合使用来处理实际请求,因此我认为我应该使用该observeOn(AndroidSchedulers.mainThread())方法Toast在主线程上创建。问题是(由于服务器的原因)我可能不得不重新发送请求,在这种情况下,我必须postRequest()再次调用该方法。

然后,此新请求现在位于主线程上。因此,为了避免使用该subscribeOn(Schedulers.io())方法,考虑到Service已经在自己的线程上,这似乎是一种浪费。

是否有指定的方式Observable应该subscribeOn()Service线程?还是应该仅继承子类Service而不IntentService使用io线程?

private void postRequest(String title, LatLng location,
                         String description, MultipartBody.Part attachment) {
    mNetworkService.postRequest(title, location.latitude, location.longitude,
            description, attachment).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(response -> {
                if (response.status() == 1) {
                    ToastUtil.makeText(getApplicationContext(), "Request Sent");
                    stopSelf();
                } else {
                    postRequest(title, location, description, attachment);
                }
            });
}
Run Code Online (Sandbox Code Playgroud)

Jah*_*old 5

我不确定IntentService我自己该如何使用an,但是肯定可以在Rx中使用其线程。

IntentService使用Looper进行工作。如果您真正了解一下内部结构AndroidSchedulers.mainThread(),则可以看到它实际上是从主线程循环程序创建调度程序的。您要做的是从IntentService Looper创建一个调度程序。

您可以使用:

Scheduler intentScheduler = AndroidSchedulers.from(Looper.myLooper());
Run Code Online (Sandbox Code Playgroud)

然后,您可以执行以下操作:

.observerOn(intentScheduler)
Run Code Online (Sandbox Code Playgroud)

要么

.subscribeOn(intentScheduler)
Run Code Online (Sandbox Code Playgroud)

并且它应该使用IntentService的线程