【发布时间】:2021-05-01 23:34:50
【问题描述】:
我有一个奇怪的用例,我需要跟踪所有以前发出的事件。
感谢 ReplaySubject,到目前为止它运行良好。在每个新订阅者上,此主题都会重新发出之前的所有事件。
现在,对于特定场景,我需要能够只提供最新发布的事件(有点像 BehaviorSubject),但保持源相同的事件。
这是我正在努力实现的目标:stackblitz
import { ReplaySubject, BehaviorSubject, from } from "rxjs";
class EventManager {
constructor() {
this.mySubject = new ReplaySubject();
}
publish(value) {
this.mySubject.next(value);
}
fullSubscribe(next, error, complete) {
return this.mySubject.subscribe(next, error, complete);
}
subscribe(next, error, complete) {
return this.mySubject.pipe(/* an operator to get the last one on new subscribe */).subscribe(next, error, complete);
}
}
const myEventManager = new EventManager();
myEventManager.publish("Data 1");
myEventManager.publish("Data 2");
myEventManager.publish("Data 3");
myEventManager.fullSubscribe(v => {
console.log("SUB 1", v);
});
myEventManager.subscribe(v => {
console.log("SUB 2", v);
});
谢谢
【问题讨论】:
-
RxJS#
last()操作符会这样做 -
@MrkSef 不完全正确。
last()不会按照他们要求的方式工作,它只会在可观察对象完成之前输出最后发布的事件。 OP 要求当订阅ReplaySubject时,“热”主题立即发出最后一个发布的事件(如BehaviorSubject),而不是像默认一样发布给它的所有事件。 -
@PatrickRoberts 好点!好的,使用 RxJS#
debounceTime(0)。我认为0应该在这里工作,因为回放是同步发生的。如果没有,他可以将去抖时间延长一点。 -
我想到了 debounceTime(0),问题是如果后续发射发生在同一个滴答上,只会收到最后一个。
标签: javascript rxjs replaysubject