How do I stop Observable.Timer() or Observable.Interval() automatically after certain period of time

前端 未结 1 1639
难免孤独
难免孤独 2021-01-29 02:35
public function(id: number) {
    this.periodicCheckTimer = Observable.timer(10000, 5000).subscribe(
        () => {
          let model = this.find(id);
          if         


        
1条回答
  •  迷失自我
    2021-01-29 03:26

    I didn't test it out, but here's an alternative to your proposal with the stop after 5mn :

    function (id: number) {
      // emit a value after 5mn
      const stopTimer$ = Observable.timer(5 * 60 * 1000);
    
      Observable
        // after 10s, tick every 5s
        .timer(10000, 5000)
        // stop this observable chain if stopTimer$ emits a value
        .takeUntil(stopTimer$)
        // select the model
        .map(_ => this.find(id))
        // do not go further unless the model has a property 'isActivated' truthy
        .filter(model => model['isActivated'])
        // only take one value so we don't need to manually unsubscribe
        .first()
        .subscribe();
    }
    

    0 讨论(0)
提交回复
热议问题