Angular、Promise、RxJSにおける「What is the difference between Promises and Observables?」
Angular、Promise、RxJSにおける「What is the difference between Promises and Observables?」
Promise
Promiseは、非同期処理の完了を待つための仕組みです。処理が完了したら、成功または失敗の結果を返します。
特徴:
- 単一の値またはエラーを返す
- 状態は「完了」または「失敗」の2つのみ
- 処理のキャンセルはできない
- ネストが複雑になりやすい
例:
const promise = fetch('https://api.example.com/data');
promise.then(response => {
// 成功時の処理
}).catch(error => {
// 失敗時の処理
});
Observable
Observableは、非同期処理のデータストリームを表す仕組みです。時間経過とともに複数の値を発行し、購読者はその値を受け取ることができます。
- 複数の値を発行できる
- 状態は「完了」、「失敗」、「継続」の3つ
const observable = RxJS.interval(1000);
observable.subscribe(value => {
// 1秒ごとに値を受け取る
});
AngularにおけるPromiseとObservable
Angularは、PromiseとObservableの両方をサポートしています。
- Promise: コンポーネントの初期化など、単一の値を取得する必要がある場合に使用
- Observable: データのストリーミングなど、複数の値を取得する必要がある場合に使用
- コンポーネントの初期化時にAPIからデータを取得する: Promise
- リアルタイムで更新されるデータを表示する: Observable
まとめ
PromiseとObservableは、それぞれ異なる強みを持つ非同期処理のための仕組みです。
- Promise: 単一の値を取得する場合に適している
Promise
// コンポーネントの初期化時にAPIからデータを取得する
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: any;
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('https://api.example.com/data').subscribe(data => {
this.data = data;
});
}
}
Observable
// リアルタイムで更新されるデータを表示する
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { interval } from 'rxjs/observable/interval';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
count: number = 0;
constructor() {}
ngOnInit() {
const observable = interval(1000);
observable.subscribe(value => {
this.count = value;
});
}
}
- 上記のサンプルコードは、あくまで基本的な使い方を示したものです。
- より複雑な処理を行う場合は、PromiseやObservableのより高度な機能を利用する必要があります。
- 詳細については、AngularやRxJSの公式ドキュメントを参照してください。
Angular、Promise、RxJSにおける「What is the difference between Promises and Observables?」の他の解説方法
アニメーション
- Promise: アニメーションの完了を待つ
- Observable: アニメーションの状態変化を監視
イベント処理
- Promise: イベントの発生を待つ
- Observable: イベントストリームを購読
データのストリーミング
- Promise: データのチャンクを取得
- Observable: データストリームをリアルタイムで受信
メタファー
- Promise: 手紙の配達
- Observable: テレビ番組の視聴
図表
- Observable: データの流れ図
対話型デモ
- Promise: ボタンをクリックして結果を表示
- Observable: スライダーを動かして値の変化を確認
チュートリアル
- Promise: Promiseの基本的な使い方を学ぶ
- Observable: Observablesの基本的な使い方を学ぶ
ユースケース
- Promise: ユーザー認証
アンケート
- Promise: どちらの方が使いやすいか
- Observable: どちらの方が汎用性が高い
angular promise rxjs