Subject
Subject is a special type of observable, which allows the value of the multicast many observers
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 variant, requires an initial value and its current value will be issued at the time of subscription.
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 variant emits only value only when completed. When finished, it will issue its latest value to all observers.
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
Can "replay" old values or sent to new subscribers. Which buffers a certain amount of value, in addition to the existing subscriber to send new values, the values will be sent immediately to any new subscriber.
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);