1
我裹着的AsyncTask類如何組織異步調用的鏈RxJava2方式
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
if (NetworkUtils.isNetworkConnected(mContext))
mIndicatorTable.sync().blockingGet();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
try {
final MobileServiceList<IndicatorModel> results = mIndicatorTable.table().read(null).blockingGet();
if (isViewAttached()) {
getMvpView().refreshIndicatorList(results);
getMvpView().hideLoading();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
};
mIndicatorTable.sync()
和mIndicatorTable.table().read(null)
都返回Single<Boolean>
下一個代碼。 mIndicatorTable.sync()
- 如果網絡不可用,則將本地存儲與遠程存儲同步,如果網絡不可用,那麼我們在網絡準備就緒時使用mIndicatorTable.table().read(null)
從本地存儲讀取 - 我們執行同步,然後從本地存儲讀取(我們不關心同步取消或中斷)。畢竟,我們應該調用View來刷新RecycleView。它如何與RxJava2一起實現?
#UPDATE
工作版本
getDataManager().syncAll()
.onErrorResumeNext(Single.just(false))
.flatMap(list -> toSingle(mIndicatorTable.getTable().read(null)))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(results -> {
if (isViewAttached()) {
getMvpView().refreshIndicatorList(results);
getMvpView().hideLoading();
}
})
謝謝你的解決方案。但在這種情況下,'.sync'失敗,那麼'.read'永遠不會執行,我是對的。在我的情況''.read'必須執行,不管.sync'的結果如何(失敗或成功) –
在這種情況下,你可以在同步後捕獲:http://reactivex.io/documentation/operators/catch.html –
由於' sync'是一個'Single',它也有可能是由一個「假」值表示的失敗,而不是一個錯誤。 –