一 Subject主題
Subject是Observable的子類。- Subject是多播的,允許將值多播給多個觀察者。普通的 Observable 是單播的。
在 Subject 的內部,subscribe
不會調用發送值的新執行。它只是將給定的觀察者注冊到觀察者列表中,類似於其他庫或語言中的 addListener
的工作方式。
要給 Subject 提供新值,只要調用 next(theValue)
,它會將值多播給已注冊監聽該 Subject 的觀察者們。
import { Component, OnInit } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'app-subject', templateUrl: './subject.component.html', styleUrls: ['./subject.component.css'] }) export class SubjectComponent implements OnInit { constructor() { } ngOnInit() { const subject: Subject<string> = new Subject<string>(); const subscriptionA: Subscription = subject.subscribe( (val: string) => { console.log(`observerA: ${val}`); } ); const subscriptionB: Subscription = subject.subscribe( (val: string) => { console.log(`observerB: ${val}`); } ); subject.next('Mikey'); subject.next('Leo'); subscriptionA.unsubscribe(); // 取消訂閱 subscriptionB.unsubscribe(); // 取消訂閱 subject.next('Raph'); subject.complete(); } }
每個 Subject 都是觀察者。 - Subject 是一個有如下方法的對象: next(v)
、error(e)
和 complete()
,可以把 Subject 作為參數傳給任何 Observable 的 subscribe
方法。
import { Component, OnInit } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { from } from 'rxjs/observable/from'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'app-subject', templateUrl: './subject.component.html', styleUrls: ['./subject.component.css'] }) export class SubjectComponent implements OnInit { constructor() { } ngOnInit() { const subject: Subject<string> = new Subject<string>(); const subscriptionA: Subscription = subject.subscribe( (val: string) => { console.log(`observerA: ${val}`); } ); const subscriptionB: Subscription = subject.subscribe( (val: string) => { console.log(`observerB: ${val}`); } ); const observable: Observable<string> = from(['Raph', 'Don']); observable.subscribe(subject); } }