如何重播可观察的?

时间:2015-11-18 15:08:28

标签: rx-java

我有这段代码:

Observable<Contact> phoneContactsObservable = Observable.create(new Observable.OnSubscribe....
ReplaySubject subject = ReplaySubject.create();
phoneContactsObservable.subscribe(subject)
Observable.combineLatest(subject,(PublishSubject<List>) getContacts(), new Func2<....).subscribe()
Observable.combineLatest(subject,(PublishSubject<List>)getFBContacts(), new Func2<....).subscribe()

如果我在getContacts中出现错误,那么Func2中的getFBContacts无法运行,然后我会执行一些方法并希望重新运行此Observables

我该怎么做?

1 个答案:

答案 0 :(得分:0)

你有可观察的doOn...)的钩子 - 比如doOnErrordoOnTerminate甚至是doOnSubscribe(我会尝试使用它来永远不会导致误差)。

也就是说,docs中有一个简单的重试延迟模式的例子。请注意,它不会在同一个元素上重试,而是通过重新订阅observable在下一个元素上重试:

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);

会给:

subscribing
delay retry by 1 second(s)
subscribing
delay retry by 2 second(s)
subscribing
delay retry by 3 second(s)
subscribing