Home > database >  Angular Rxjs takeWhile operator occurs only once
Angular Rxjs takeWhile operator occurs only once

Time:12-09

I try to keep sending request to the server with delay, but I When I put console log, I see that it does not occurs second time.

Here is my code:

this.siteStatusMessage.pipe(
      map(messageData => JSON.parse(JSON.stringify(messageData))),
      takeWhile(() => this.isAlive),
      delay(3000)
    ).subscribe();

What am I doing wrong?

CodePudding user response:

For what I understand, you're trying to use delay(3000) to execute the observable every 3 seconds.

The delay operator, as its name states, just delays the emission of notifications. So in your example the observable will execute just once but emitting its notifications 3 seconds later than normal.

To execute the observable every 3 seconds, you need to use an interval.

interval(3000).pipe(
  switchMap((_) => this.siteStatusMessage.pipe(
      map(messageData => JSON.parse(JSON.stringify(messageData)))
  ),
  takeWhile(() => this.isAlive),
)

CodePudding user response:

takeWhile is taking a boolean, your functionlity seems like you want to use takeUntil(this.isAlive) in this case isAlive must be a subject/Observable a notifier. Requirement is quite vague please provide more details.

CodePudding user response:

Since it looks like you want to delay the requests by 3 seconds each and keep doing them until you set your isAlive flag to false, you'd be better off with the interval pipe instead of delay.

I've compiled a script here for you to play around with. In the example, the string will be emitted every 3 seconds, until the flag turns false. You just need to replace the dummy observable with yours.

  • Related