我創建了一個簡單的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);
}
});
}