如何重试当重试抛出异常的流时

时间:2018-06-15 13:55:51

标签: rx-java rx-java2

我正在尝试使用retryWhen处理一个非常基本的流程。 我发射了3个Flowable,其中一个抛出IOException,在这种情况下,我会触发重试最多2次。 问题是在重试时它会重新启动所有内容。使其他可流动的内容重新发出。 这是我的代码:

Flowable.just("AA", "BB", "CC")//
        .flatMap(station -> getStation(station))//
        .retryWhen( RetryWhen
                     .maxRetries(2)
                     .retryWhenInstanceOf(IOException.class)
                     .build())
        .subscribe(//
            station -> System.out.println("Received Availability for station=" + station),
            error -> System.err.println("Failed with error=" + error.getMessage()),
            () -> System.out.println("Completed!")//
        );

private Flowable<String> getStation(String station)
  {
    if (station.equals("CC"))
    {
      System.err.println("Failed staton=" + station + " --> Going to retry");
      return Flowable.error(new IOException("Server for station=" + station + " is down!"));
    }

    System.out.println("Querying for Station=" + station);

    return Flowable.just(station);
  }

如何调整它以仅生成抛出异常重试的那个?

修改: 根据反馈,我已将代码更改为在每个Flowable实例上重试:

 Flowable<String> flw1 = getStationAvailability("AA");
        Flowable<String> flw2 = getStationAvailability("BB");
        Flowable<String> flw3 = getStationAvailability("CC");

      Flowable.concat(//
            flw1.retryWhen(RetryWhen.maxRetries(2).retryWhenInstanceOf(IOException.class).build()),
            flw2.retryWhen(RetryWhen.maxRetries(2).retryWhenInstanceOf(IOException.class).build()),
            flw3.retryWhen(RetryWhen.maxRetries(2).retryWhenInstanceOf(IOException.class).build())//
        ).subscribe(//
            station -> System.out.println("Received Availability for station=" + station),
            error -> System.err.println("Failed with error=" + error.getMessage()),// 
            () -> System.out.println("Completed!")//
        );

但是,结果是它根本没有重试。 对此的任何见解? 谢谢!

1 个答案:

答案 0 :(得分:1)

您需要将retryWhen()运算符放在各个可观察对象的观察者链上。

Flowable.just(“AA”,“BB”,“CC”)//         .flatMap(station - &gt; getStation(station)           .retryWhen(retryStrategy))//       .subscribe(...);

这样,重新订阅只发生在一个观察链上。

相关问题