retrofit+okhttp+rxjava处理ouanth2 token过期时,请求刷新token并重新请求原接口。
这种方法只适用于http code返回错误的情况,如果是业务内code返回则需要用okhttp拦截来实现。
关键操作符为retryWhen,在错误时重新请求。
Observable.just(null)
.flatMap(new Func1<Object, Observable<T>>() {
@Override
public Observable<T> call(Object o) {
return RetrofitService.getInstance().createApi(UserApi.class).getPersonInfo();//请求的接口,例:获取用户信息
}
})
.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> observable) {
return observable
.flatMap(new Func1<Throwable, Observable<?>>() {
@Override
public Observable<?> call(Throwable throwable) {
if (throwable instanceof HttpException && ((HttpException) throwable).code() == 401) { //返回401,token过期
return RetrofitService.getInstance().createApi(OauthApi.class).refreshToken(refreshToken)//刷新token请求
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io()) //同步
.doOnNext(new Action1<TokenResult>() {
@Override
public void call(TokenResult tokenResult) {
//获取新的token并保存
//TokenBean tokenBean = tokenResult.data;
//saveToken(tokenBean);
}
});
}
return Observable.error(throwable);
}
});
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(UseCaseSubscriber); //传入业务的subscriber