BehaviorSubject
BehaviorSubject 是 Subject 的一個(gè)變種绿满,他的特點(diǎn)是會(huì)存儲(chǔ)當(dāng)前值寺滚,
const subject = new rxjs.Subject();
subject.subscribe((next => {
console.log(next);
}));
// 去掉下面的注釋才會(huì)輸出結(jié)果
// subject.next(1);
而 BehaviorSubject 一旦 subscribe 就會(huì)執(zhí)行纹安,可以在定義時(shí)要初始化值。
const subject = new rxjs.BehaviorSubject(0);
// 會(huì)輸出 0
subject.subscribe((next => {
console.log(next);
}));
ReplaySubject
在某些時(shí)候我們會(huì)希望 Subject 代表事件斟览,但又能在新訂閱時(shí)重新發(fā)送最后的幾個(gè)元素扫外,這時(shí)我們就可以用 ReplaySubject,范例如下
const count = 1;
const subject = new rxjs.ReplaySubject(count);
var observerA = {
next: value => console.log('A next: ' + value),
error: error => console.log('A error: ' + error),
complete: () => console.log('A complete!')
}
var observerB = {
next: value => console.log('B next: ' + value),
error: error => console.log('B error: ' + error),
complete: () => console.log('B complete!')
}
subject.subscribe(observerA);
subject.next(1);
// "A next: 1"
subject.next(2);
// "A next: 2"
subject.next(3);
// "A next: 3"
setTimeout(() => {
subject.subscribe(observerB);
// 根據(jù)傳入 n 的不同
// "B next: 2"
// "B next: 3"
},3000)
ReplaySubject(1) 不等同于 BehaviorSubject嵌莉,BehaviorSubject 在建立時(shí)就會(huì)有起始值进萄,比如 BehaviorSubject(0) 起始值就是 0,BehaviorSubject 是代表著狀態(tài)而 ReplaySubject 只是事件的重放而已锐峭。
AsyncSubject
AsyncSubject 是最怪的一個(gè)變形中鼠,他有點(diǎn)像是 operator last,會(huì)在 subject 結(jié)束后送出最后一個(gè)值沿癞,范例如下
const subject = new rxjs.AsyncSubject();
var observerA = {
next: value => console.log('A next: ' + value),
error: error => console.log('A error: ' + error),
complete: () => console.log('A complete!')
}
var observerB = {
next: value => console.log('B next: ' + value),
error: error => console.log('B error: ' + error),
complete: () => console.log('B complete!')
}
subject.subscribe(observerA);
// 執(zhí)行 next 并不會(huì)輸出值
subject.next(1);
subject.next(2);
subject.next(3);
// 必須執(zhí)行 complete 才會(huì)輸出值
subject.complete();
setTimeout(() => {
subject.subscribe(observerB);
// "B next: 2"
// "B next: 3"
},3000)
AsyncSubject 會(huì)在 Subject 結(jié)束后才送出最后一個(gè)值援雇,其實(shí)這個(gè)行為跟 Promise 很像,都是等到事情結(jié)束后送出一個(gè)值椎扬,實(shí)際上我們非常少用到 AsyncSubject惫搏,絕大部分的時(shí)候都是使用 BehaviorSubject 跟 ReplaySubject 或 Subject。
參考:
https://segmentfault.com/a/1190000005069851
https://ithelp.ithome.com.tw/articles/10188677