我試圖使用RxJava和Retrofit(2.3)進行請求。我期待如果有任何錯誤,我可以重試或向客戶端顯示消息。然而,我注意到有時我有一個SocketException,導致不會調用onError,顯然該請求的訂閱者只是退訂而沒有調用任何其他(而不是onComplete onError)。任何人都知道爲什麼會發生這種情況,我怎樣才能以通用的方式解決這個問題(沒有簡單地做onUnsubscribe()並檢查observable是否沒有發送onError或onComplete)?SocketException在沒有onError的情況下取消訂閱請求
在我的界面我有這樣的事情:
@GET("userInfo")
Observable<List<UserInfo>> getUserInfo(@Header("token") String token);
這是我創造我觀察到:
public Observable<UserModel> requestUserInfo(final String token) {
return mService.getUserInfo(token)
.retryWhen(new RetryWithDelay(HTTP_RETRIES), HTTP_TIME_BETWEEN_RETRIES)))
.flatMap(new Func1<List<UserInfo>, Observable<UserModel>() {
@Override
public Observable<UserModel> call(List<UserInfo> userInfo) {
return Observable.just(new UserModel(userInfo));
}
});
}
------ UPDATE ------ -
這就是我如何在我的演示者上調用requestUserInfo方法
private CompositeSubscription mCompositeSubscription = null;
public PresenterX(ViewX view) {
...
mCompositeSubscription = new CompositeSubscription();
}
public void getUserModel() {
String userToken = new AccessModel().getUserToken();
mCompositeSubscription.add(mNetworkRequestModel.requestUserInfo(userToken)
.flatMap(new Func1<UserModel, Observable<UserModel>>() {
@Override
public Observable<UserModel> call(UserModel userModel) {
if (userModel != null) {
saveUserModel(userModel); //sync saving
return Observable.just(userModel);
} else {
return Observable.error(new SaveException());
}
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<UserModel>() {
@Override
public void onCompleted() {
Log.i(TAG, "Subscriber was completed")
}
@Override
public void onError(Throwable e) {
Log.i(TAG, "Subscriber called onError")
mView.handleErrors(e);
}
@Override
public void onNext(UserModel userModel) {
Log.i(TAG, "Subscriber called onNext")
mView.populateUserInfo(userModel);
}
}));
}
//called by activity when onDestroyMethod is called
//I assume this is not called as I have other requests running parallelly to this getUserModel() and they are not terminated, despite having other compositeSubscription to manage those
public void onDestroy(){
mCompositeSubscription.clear();
}
因爲我有一個HttpLoggingInterceptor,這是在請求突然停止時打印給我的唯一日誌。
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
LOG.info(Thread.currentThread(), String.format("%s", message));
}
});
這裏是日誌例外:
I/ExampleApp-ApiClient(21338): : Thread: 1343 | <-- HTTP FAILED: java.net.SocketException: Socket closed
請包含代碼,其中調用Observable.subscribe。取消訂閱或「onError」問題發生在這些端點。 – Kiskae