P
P
Programep2019-05-30 19:58:11
JavaScript
Programep, 2019-05-30 19:58:11

How to pause and run intrerval in RxJS?

Good afternoon!
Please tell me how to solve this problem. Also, please advise guides on RxJS with simple examples.

  1. I am developing a project on Angular 7.0.4 and rxjs 6.3.3
  2. the page has two subscriptions for two intervals.
    1st: interval(10000); inside subscribe of this interval, they process http requests.
    2nd: interval(1000); this interval changes the second_to_event variable to -1. When the second_to_event == 0 condition is met, you need to:
    1. pause this subscription
    2. make http request
    3. in case of successful completion of the http request, reset the second_to_event variable, start the subscription


Through google I found that switchMap is used for this : here is an example . But in this example, an Observable is created for an event, and in my case, as I understand it, you need to make an Observable for a condition.
Here is the code I currently have:
export class GameComponent implements OnInit, OnDestroy {

  reloadGameInfo = interval(10000);
  reloadGameInfoSubscription: Subscription;
  stepTimer = interval(1000);
  stepTimerSubscription: Subscription;
  
  ngOnInit(){
    this.reloadGameInfoSubscription = this.reloadGameInfo.subscribe(() => {      
      this.gameService.getInfoGame(this.current_game.auth_key)
        .subscribe((response: Game) => {          
          if (this.current_game.status_id == gameStatusCode.two_player_in_game) {            
            if (!this.stepTimerSubscription) {
              this.stepTimerSubscription = this.stepTimer.subscribe(() => {                                
                if (--this.current_game.seconds_for_step == 0) {
                  this.stepTimerSubscription.unsubscribe();                  
                }
              });
            }
          }
        });
    });
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-05-30
@Programep

reloadGameInfo = interval(10000);
stepTimer = interval(1000);
second_to_event = 100;

this.stepTimer.subscribe(() => {
  this.second_to_event = this.second_to_event >= 0 ? this.second_to_event - 1 : 0;
  if (this.second_to_event === 0) {
    // make request at second_to_event equals to 0 and set second_to_event if request success
  }
});

this.reloadGameInfo.pipe(
  filter(() => this.second_to_event > 0
)
  .subscribe(() => {
    // do 10000 periodic task
  })

well, something like this,
switchMap will not work, it completes the previous observable in the chain, i.e. your interval will end. If you don't want to call subscript requests, you can use flatMap

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question