Answers:
一个BehaviorSubject拥有一个值。订阅后,它将立即发出该值。主题没有值。
主题示例(使用RxJS 5 API):
const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));
控制台输出将为空
BehaviorSubject示例:
const subject = new Rx.BehaviorSubject();
subject.next(1);
subject.subscribe(x => console.log(x));
控制台输出:1
此外:
BehaviorSubject
可以使用初始值创建:新 Rx.BehaviorSubject(1)
ReplaySubject
是否要让主体保留一个以上的值BehaviourSubject将在订阅上返回初始值或当前值
var bSubject= new Rx.BehaviorSubject(0); // 0 is the initial value
bSubject.subscribe({
next: (v) => console.log('observerA: ' + v) // output initial value, then new values on `next` triggers
});
bSubject.next(1); // output new value 1 for 'observer A'
bSubject.next(2); // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription
bSubject.subscribe({
next: (v) => console.log('observerB: ' + v) // output current value 2, then new values on `next` triggers
});
bSubject.next(3);
输出:
observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3
主题不返回“订阅”上的当前值。它仅在.next(value)
调用时触发并返回/输出value
var subject = new Rx.Subject();
subject.next(1); //Subjects will not output this value
subject.subscribe({
next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
next: (v) => console.log('observerB: ' + v)
});
subject.next(2);
subject.next(3);
在控制台上显示以下输出:
observerA: 2
observerB: 2
observerA: 3
observerB: 3
subject.next(3);
我刚刚创建了一个项目,解释了所有主题之间的区别:https :
//github.com/piecioshka/rxjs-subject-vs-behavior-vs-replay-vs-async
它可能会帮助您理解。
import * as Rx from 'rxjs';
const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.
const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);
const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.
const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2
BehaviorSubject
将可观察对象发出的最后一个值保留在内存中。一个普通的Subject
没有。
BehaviorSubject
就像ReplaySubject
缓冲区大小为1。