我创建了一个简单的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);
}
});
}