Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

angular - Observable repeatWhen & retryWhen other observable is true (network is connected)

Example code:

const networkConnected = new BehaviorSubject<boolean>(false);

setTimeout(networkConnected.next(true), 10000);

webSocket('ws://localhost:4949')
  .pipe(
    retryWhen(errors => errors.pipe(delay(10000), filter(() => networkConnected.value === true))),
    repeatWhen(completed => completed.pipe(delay(10000), filter(() => networkConnected.value === true))),
    tap(a => console.log('Connecting...'))
  ).subscribe(
    message=> console.info(message),
    error => console.error(error),
    () => console.warn('Completed'),
  );

I searched for one hour and wasnt able to find one other person who want the same.

There is a WebSocket which should be reconnected whenever it loses the connection. So I integrated a retryWhen. The repeatWhen is for the case that the WebSocket completes...

And now I want to add a logic to only reconnect (retry/repeat) when the internet connection is OK. So when my networkConnected observable is true. When it's false the reconnect (retry/repeat) should wait until its true.

Maybe something with zip? Or mergeMap? Or I add a timer which runs every second and check if the value is true with skipUntil.

But I think someone of you have a better solution ??

question from:https://stackoverflow.com/questions/65871826/observable-repeatwhen-retrywhen-other-observable-is-true-network-is-connected

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would have the networkConnectivity be a precondition for the websocket to be set up:

networkConnected
  .pipe(
    // do not want to re-open the websocket when the network is still connected
    distinctUntilChanged(),
    // when connected open the websocket, otherwise noop and wait till connected
    switchMap(isConnected => isConnected ? openWebsocket() : empty())
  )
  .subscribe(
    message=> console.info(message),
    error => console.error(error),
    () => console.warn('Completed')
  );

openWebsocket = () => {
  return webSocket('ws://localhost:4949')
    .pipe(
      // this works for websocket errors while networkConnected=true
      retryWhen(errors => errors.pipe(delay(10000)),
      repeatWhen(completed => completed.pipe(delay(10000)),
      tap(a => console.log('Connecting...'))
    );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...