可观察,仅在完成时重试错误和缓存

Pla*_*ato 15 rx-java rx-android

我们可以使用cache()运算符来避免多次执行长任务(http请求),并重用其结果:

Observable apiCall = createApiCallObservable().cache(); // notice the .cache()

---------------------------------------------
// the first time we need it
apiCall.andSomeOtherStuff()
               .subscribe(subscriberA);

---------------------------------------------
//in the future when we need it again
apiCall.andSomeDifferentStuff()
               .subscribe(subscriberB);
Run Code Online (Sandbox Code Playgroud)

第一次执行http请求,但第二次,因为我们使用了cache()运算符,请求将不会被执行,但我们将能够重用第一个结果.

第一个请求成功完成时,此工作正常.但是如果在第一次尝试中调用了onError,那么下次新订阅者订阅同一个observable时,将再次调用onError而不再尝试http请求.

我们要做的是,如果第一次调用onError,那么下次有人订阅同一个observable时,将从头开始尝试http请求.即,observable将仅缓存成功的api调用,即调用onCompleted的调用.

关于如何进行的任何想法?我们尝试使用retry()和cache()运算符没有太多运气.

ndo*_*ori 8

好吧,对于任何仍然感兴趣的人,我认为我有一个更好的方法来实现它与rx.

关键注意事项是使用onErrorResumeNext,它可以让你在出现错误时替换Observable.所以看起来应该是这样的:

Observable<Object> apiCall = createApiCallObservable().cache(1);
//future call
apiCall.onErrorResumeNext(new Func1<Throwable, Observable<? extends Object>>() {
    public Observable<? extends Object> call(Throwable throwable) {
        return  createApiCallObservable();
        }
    });
Run Code Online (Sandbox Code Playgroud)

这样,如果第一个呼叫失败,未来的呼叫将只召回它(仅一次).

但是每个尝试使用第一个observable的调用者都会失败并提出不同的请求.

你引用了原始的observable,让我们更新它.

所以,一个懒惰的吸气者:

Observable<Object> apiCall;
private Observable<Object> getCachedApiCall() {
    if ( apiCall == null){
        apiCall = createApiCallObservable().cache(1);
    }
    return apiCall;
}
Run Code Online (Sandbox Code Playgroud)

现在,如果前一个失败将重试的getter:

private Observable<Object> getRetryableCachedApiCall() {
    return getCachedApiCall().onErrorResumeNext(new Func1<Throwable, Observable<? extends Object>>() {
        public Observable<? extends Object> call(Throwable throwable) {
            apiCall = null;
            return getCachedApiCall();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意,它每次调用时只会重试一次.

所以现在你的代码看起来像这样:

---------------------------------------------
// the first time we need it - this will be without a retry if you want..
getCachedApiCall().andSomeOtherStuff()
               .subscribe(subscriberA);

---------------------------------------------
//in the future when we need it again - for any other call so we will have a retry
getRetryableCachedApiCall().andSomeDifferentStuff()
               .subscribe(subscriberB);
Run Code Online (Sandbox Code Playgroud)


Pla*_*ato 7

在扩展akarnokd的解决方案之后,这是我们最终得到的解决方案:

public class OnErrorRetryCache<T> {

    public static <T> Observable<T> from(Observable<T> source) {
         return new OnErrorRetryCache<>(source).deferred;
    }

    private final Observable<T> deferred;
    private final Semaphore singlePermit = new Semaphore(1);

    private Observable<T> cache = null;
    private Observable<T> inProgress = null;

    private OnErrorRetryCache(Observable<T> source) {
        deferred = Observable.defer(() -> createWhenObserverSubscribes(source));
    }

    private Observable<T> createWhenObserverSubscribes(Observable<T> source) 
    {
        singlePermit.acquireUninterruptibly();

        Observable<T> cached = cache;
        if (cached != null) {
            singlePermit.release();
            return cached;
        }

        inProgress = source
                .doOnCompleted(this::onSuccess)
                .doOnTerminate(this::onTermination)
                .replay()
                .autoConnect();

        return inProgress;
    }

    private void onSuccess() {
        cache = inProgress;
    }

    private void onTermination() {
        inProgress = null;
        singlePermit.release();
    }
}
Run Code Online (Sandbox Code Playgroud)

我们需要缓存来自Retrofit的http请求的结果.所以这是创建的,其中一个可观察的内容会记住一个项目.

如果观察者在执行http请求时订阅,我们希望它等待并且不执行两次请求,除非正在进行的请求失败.为此,信号量允许单个访问创建或返回高速缓存的observable的块,如果创建了新的observable,我们将等待,直到该终止.可在此处找到上述测试


aka*_*okd 5

你必须做一些状态处理。这是我如何做到这一点:

public class CachedRetry {

    public static final class OnErrorRetryCache<T> {
        final AtomicReference<Observable<T>> cached = 
                new AtomicReference<>();

        final Observable<T> result;

        public OnErrorRetryCache(Observable<T> source) {
            result = Observable.defer(() -> {
                for (;;) {
                    Observable<T> conn = cached.get();
                    if (conn != null) {
                        return conn;
                    }
                    Observable<T> next = source
                            .doOnError(e -> cached.set(null))
                            .replay()
                            .autoConnect();

                    if (cached.compareAndSet(null, next)) {
                        return next;
                    }
                }
            });
        }

        public Observable<T> get() {
            return result;
        }
    }

    public static void main(String[] args) {
        AtomicInteger calls = new AtomicInteger();
        Observable<Integer> source = Observable
                .just(1)
                .doOnSubscribe(() -> 
                    System.out.println("Subscriptions: " + (1 + calls.get())))
                .flatMap(v -> {
                    if (calls.getAndIncrement() == 0) {
                        return Observable.error(new RuntimeException());
                    }
                    return Observable.just(42);
                });

        Observable<Integer> o = new OnErrorRetryCache<>(source).get();

        o.subscribe(System.out::println, 
                Throwable::printStackTrace, 
                () -> System.out.println("Done"));

        o.subscribe(System.out::println, 
                Throwable::printStackTrace, 
                () -> System.out.println("Done"));

        o.subscribe(System.out::println, 
                Throwable::printStackTrace, 
                () -> System.out.println("Done"));
    }
}
Run Code Online (Sandbox Code Playgroud)

它的工作原理是缓存一个完全成功的源并将其返回给每个人。否则,(部分)失败的源将创建缓存,下一个调用观察者将触发重新订阅。