2017-04-18 185 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

的線程