我希望在我的Java应用程序中用Observable包装经过身份验证的调用,如果需要,Observable会在发出请求之前重新授权我的用户。我在Objective-C中用形状代码博客中的这种方法对ReactiveCocoa做了类似的事情:
- (RACSignal *)doRequestAndRefreshTokenIfNecessary:(RACSignal *)requestSignal {
return [requestSignal catch:^(NSError *error) {
// Catch the error, refresh the token, and then do the request again.
BOOL hasRefreshToken = [UserManager sharedInstance].refreshToken != nil;
BOOL httpCode401AccessDenied = error.code == -1011;
if (httpCode401AccessDenied && hasRefreshToken) {
NSLog(@"Will attempt to refresh access token.");
return [[[self refreshToken] ignoreValues] concat:requestSignal];
}
return requestSignal;
}];
}
RACSignal是Observable的ReactiveCocoa类似物。该方法创建一个RACSignal,该RACSignal将捕获由初始请求发出的任何错误,并且如果该错误与给定标准匹配(在这种情况下,访问被拒绝并且存在可用的身份验证令牌(,则透明地触发新的RACSignal以使用刷新令牌,然后重新发送原始信号。
RxJava是否提供类似的设施?在Combinating Observables文档中,我找不到任何类似于catch:
的内容。
RxJava中似乎没有任何预先存在的东西,但这似乎可以很好地完成任务(相当直接地翻译自ReactiveCocoa的捕获(:
public class CatchObservable {
public interface CaughtErrorHandler {
public Observable<?> onError(Throwable throwable);
}
public static <T> Observable catchObserver(final Observable<T> observable, final CaughtErrorHandler errorHandler) {
return Observable.create(new Observable.OnSubscribeFunc<T>() {
@Override
public Subscription onSubscribe(final Observer<? super T> subscriber) {
return observable.subscribe(new Observer<T>() {
@Override
public void onCompleted() {
subscriber.onCompleted();
}
@Override
public void onError(Throwable e) {
Observable observable = errorHandler.onError(e);
observable.subscribe(subscriber);
}
@Override
public void onNext(T args) {
subscriber.onNext(args);
}
});
}
});
}
}
如此使用:
private Observable refreshAuthIfNecessary(final Observable<?> request) {
return CatchObservable.catchObserver(request, new CatchObservable.CaughtErrorHandler() {
@Override
public Observable<?> onError(Throwable throwable) {
return Observable.concat(WebServices.this.refreshAuth(), request);
}
});
}