提前退出Rx.Observable.retryWhen / timer

时间:2016-11-01 19:37:17

标签: javascript rxjs

鉴于 A 异步任务出错并且 R 已恢复。恢复开始后,我需要发布剩余的秒数以恢复,并根据需要选择以提前退出T 计时器。

基本上,我希望有类似的功能: 重新连接 N s 立即重新连接

// S - instance scope

let ws = Rx.Observable.create((obs: Rx.Observer<{}>) => {
  // A - async that may fail
  obs.error("error");
}).retryWhen((errors: Rx.Observable<{}>) => {
  // R - progress of recovery
  return Rx.Observable.timer(5000); // T timer
});

1 个答案:

答案 0 :(得分:0)

Okaaay,我终于明白了。只是张贴参考

run jsbin

console.clear();

let recoveryDelay = new Rx.Subject(Rx.Observer.create(), Rx.Observable.empty());
let recovery = new Rx.Subject(Rx.Observer.create(), Rx.Observable.empty());

let obs = Rx.Observable.create((obs) => {
  setInterval(() => {
    obs.next(Math.random());
  }, 1000);

  setTimeout(() => {
    obs.error('error');
  }, 3000);
}).retryWhen((error) => {
  return error.flatMap(() => {

    recovery.onNext('wait...');

    return Rx.Observable.create((obs) => {

      let sub = recoveryDelay.subscribe(() => {
        recovery.onNext('force continue');
        obs.next();
        obs.onCompleted();
      });

      let timeout = setTimeout(() => {
        obs.next();
        obs.onCompleted();
      }, 20000);

      return () => {
        recovery.onNext('ready');
        clearTimeout(timeout);
        sub.dispose();
      }
    });
  });
});

obs.subscribe(x => console.log(x));

recovery.subscribe(status => console.log('1 status ' + status));
recovery.subscribe(status => console.log('2 status ' + status));

setTimeout(() => {
  recoveryDelay.onNext();
}, 5000);