中安拓也のブログ

プログラミングについて書くブログ

RxJS: Observable.intervalの止め方

はじめに

一定間隔で繰り返したい時におなじみの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();
    });
  }
}

サンプルコードの動作結果はこうなります。

f:id:l08084:20180220165524p:plain

RxJS4系だとDisposable.prototype.disposeを使うらしいです(4系使ったことないので知りませんが.....)。