Как я могу подписаться и отписаться от наблюдаемой? - PullRequest
0 голосов
/ 27 мая 2019

У меня есть две функции, в которых мне нужно подписаться на наблюдаемое в первом и отписаться на него во втором. Но в моем коде я не могу получить доступ к наблюдаемой из второй функции, потому что она не входит в ее область действия.

вот мои функции:

 start() {
    this.max = this.duration;
    const interval = Observable.interval(this.selectedSprint.duration);
    interval
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
    }

    stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
    // if true logic
        }
      });
      }

Ответы [ 3 ]

2 голосов
/ 27 мая 2019

Одним из решений является сохранение подписки в вашем компоненте.

export class Component {
  interval$: Subscription;

  start() {
    this.max = this.duration;
    this.interval$ = Observable.interval(this.selectedSprint.duration)
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
  }

  stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
          this.interval$.unsubscribe();
        }
    });
  }
}

РЕДАКТИРОВАТЬ, чтобы ответить на комментарий ОП

export class Component {
  intervalSub$: Subscription;
  intervalObs: Observable<number>;

  start() {
    this.max = this.duration;
    this.intervalObs$ = Observable.interval(this.selectedSprint.duration)
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1);
   this.intervalSub$ = intervalObs.subscribe();
  }

  stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
          this.intervalSub$.unsubscribe();
        }
    });
  }
  /**
   * If you unsubscribed from the interval and you want to resume
   * (If this.isFinished is true, it won't do a thing)
   */
  resume() {
    this.intervalObs.subscribe();
  }
}
2 голосов
/ 27 мая 2019

Сохраните ссылку на вашу подписку в вашем классе с помощью this.sub = interval.[...].subscribe().

Таким образом, вы можете выполнить this.sub.unsubscribe() во второй функции.

0 голосов
/ 27 мая 2019

Если вы находитесь в классе, вы можете сохранить объект subscription, возвращаемый вызовом .subscribe(), в качестве свойства.

start() {
   this.max = this.duration;
   const interval = Observable.interval(this.selectedSprint.duration);
   interval
     .takeWhile(_ => !this.isFinished)
     .do(i => this.current += 1);
   this.intervalSubscription = interval.subscribe();
}

Это позволит вам отписаться в вашем stop методе

stop() {
    this.intervalSubscription.unsubscribe(...);
}
...