はじめに
一定間隔で繰り返したい時におなじみのsetInterval
をRxJSでかくとObservable.interval
になりますが、
setInterval
に対するclearInterval
のようにObservable.interval
を止めたい時は何を使えばいいんだろうか🤔
開発環境
Angular: 5.2.3
rxjs: 5.5.6
TypeScript: 2.5.3
angular/cli: 1.6.5
OS: darwin x64
Node: 8.1.4
他と同様にunsubscribeで停止できる
他のRxJSのsubscribe
と同様に、Observable.interval
についてもunsubscribe
で停止できます。
サンプルコード
src/app/app.component.ts
:
import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval'; import 'rxjs/add/observable/fromEvent'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { private timer: Subscription; ngOnInit() { // 1秒間隔で「interval: {現在時刻}」と出力し続ける this.timer = Observable.interval(1000) .subscribe(() => console.log(`interval: ${new Date()}`)); // クリックイベントを検知すると、 // 「interval stop!」と出力した後に // Observable.intervalが停止する Observable.fromEvent(document, 'click').subscribe(() => { console.log('interval stop!') this.timer.unsubscribe(); }); } }
サンプルコードの動作結果はこうなります。
RxJS4系だとDisposable.prototype.dispose
を使うらしいです(4系使ったことないので知りませんが.....)。