一 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);
}
}