Subject
Subject是可观察的一种特殊类型,它允许将值多播到许多观察者
import {Subject} from 'rxjs';
const l = console.log;
let x$ = new Subject<number>();
x$.subscribe(v => l(`a => ${v}`)); // 1, 2, 3
x$.next(1);
x$.next(2);
setTimeout(() => {
x$.subscribe(v => l(`b => ${v}`)); // 3
x$.next(3);
}, 2000);
BehaviorSubject
Subject的变体,需要初始值,并且在订阅时会发出其当前值。
import {BehaviorSubject} from 'rxjs';
const l = console.log;
let x$ = new BehaviorSubject<number>(0);
x$.subscribe(v => l(`a => ${v}`)); // 0, 1, 2, 3
x$.next(1);
x$.next(2);
setTimeout(() => {
// 订阅时发出当前值: 2
x$.subscribe(v => l(`b => ${v}`)); // 2, 3
x$.next(3);
}, 2000);
AsyncSubject
Subject的变体,仅在完成时才发出值。完成后,它将向所有观察者发出其最新值。
import {AsyncSubject} from 'rxjs';
const l = console.log;
let x$ = new AsyncSubject<number>();
x$.subscribe(l); // 2
x$.next(1);
x$.next(2);
x$.complete();
ReplaySubject
可“重放”或向新订阅者发出旧值。 它缓冲一定数量的值,除了向现有订户发送新值外,还将立即将这些值发送给任何新订户。
import {ReplaySubject} from 'rxjs';
const l = console.log;
let x$ = new ReplaySubject<number>();
x$.subscribe(v => l(`a => ${v}`)); // 1, 2, 3
x$.next(1);
x$.next(2);
setTimeout(() => {
// 2s后,向新的订阅发出旧的值:1,2
x$.subscribe(v => l(`b => ${v}`)); // 1, 2, 3
x$.next(3);
}, 2000);