我正在使用BehaviorSubject
存储一些数据,并在将来的某个时间将其取回。以下是一些示例代码,可重现我遇到的奇怪问题:
var subject = new BehaviorSubject<any>(undefined);
subject.next(1); // Store the value 1 into 'subject'
subject.asObservable().subscribe((data) => { console.log(data); });
// Output: 1
subject.next(2); // Store the value 2 into 'subject'
subject.asObservable().subscribe((data) => { console.log(data); });
// Output 2 \n 2 (logs twice)
subject.next(1); // Store the value 1 into 'subject'
subject.asObservable().subscribe((data) => { console.log(data); });
// Output: 1 \n 1 \n 1 (logs three times)
根据我在网上阅读的内容,我希望subject.next()
会覆盖Observable中的值,这是在做的事情,但是我不希望它返回这些多余的尾随等效值。 / p>
编辑:我不知道subscribe()类似于EventListener,只要可观察到的变化就会被调用。这是产生预期输出的代码:
var subject = new BehaviorSubject<any>(undefined);
subject.next(1); // Store the value 1 into 'subject'
subject.asObservable().subscribe((data) => { console.log(data); });
subject.next(2); // Store the value 2 into 'subject'
subject.next(1); // Store the value 1 into 'subject'