2017-04-18 182 views
0

我创建了一个简单的IntentService来上传文件和一些数据到服务器。我希望在上传完成后能够显示Toast,但我需要在主线程上才能这样做。RxJava订阅服务主题

由于我使用的改造结合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); 
       } 
      }); 
} 

回答

1

不知道我是否错过了那里的东西,但为什么不在过度使用“烤面包机”之前过滤流?即通过response.status()过滤流。如果成功,他们可以立即传递给烤面包机,否则他们会再次发送。

这可能发生在您返回到主线程之前,因此您不必从那里重新发送它。

2

我不确定使用IntentService是我如何自己去解决这个问题,但它肯定可以在Rx中使用它的线程。

IntentService使用Looper来完成它的工作。如果你真的看到了AndroidSchedulers.mainThread(),你可以看到它实际上是从主线程中创建一个调度器。你想要做的是从IntentService Looper创建一个调度器。

可以使用这样做:

Scheduler intentScheduler = AndroidSchedulers.from(Looper.myLooper()); 

然后,你可以这样做:

.observerOn(intentScheduler) 

.subscribeOn(intentScheduler) 

而且它应该使用IntentService

的线程