本文介绍了如果 retryWhen:s 重试次数用完,则捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RetryWhen 的文档 中,示例如下所示:

In the documentation for RetryWhen the example there goes like this:

Observable.create((Subscriber<? super String> s) -> {
  System.out.println("subscribing");
  s.onError(new RuntimeException("always fails"));
}).retryWhen(attempts -> {
  return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> {
      System.out.println("delay retry by " + i + " second(s)");
      return Observable.timer(i, TimeUnit.SECONDS);
  });
}).toBlocking().forEach(System.out::println);

但是如果重试用完,我该如何传播错误?

But how do I propagate the Error if the retries runs out?

添加 .doOnError(System.out::println) after retryWhen 子句没有捕获错误.它甚至发出了吗?

Adding .doOnError(System.out::println) after the retryWhen clause does not catch the error. Is it even emitted?

添加 .doOnError(System.out::println) before retryWhen 显示 always failed 所有重试.

Adding a .doOnError(System.out::println) before retryWhen displays always fails for all retries.

推荐答案

retryWhen 的文档说它向订阅者传递 onError 通知并终止.所以你可以做这样的事情:

The doc for retryWhen says that it passes onError notification to its subscribers and terminates. So you can do something like this:

    final int ATTEMPTS = 3;

    Observable.create((Subscriber<? super String> s) -> {
        System.out.println("subscribing");
        s.onError(new RuntimeException("always fails"));
    }).retryWhen(attempts -> attempts
            .zipWith(Observable.range(1, ATTEMPTS), (n, i) ->
                    i < ATTEMPTS ?
                            Observable.timer(i, SECONDS) :
                            Observable.error(n))
            .flatMap(x -> x))
            .toBlocking()
            .forEach(System.out::println);

这篇关于如果 retryWhen:s 重试次数用完,则捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 10:30