gpt4 book ai didi

javascript - 让 ReplaySubject 只返回订阅的最后一个值

转载 作者:行者123 更新时间:2023-12-03 16:57:19 26 4
gpt4 key购买 nike

我有一个奇怪的用例,我需要跟踪所有以前发出的事件。
感谢 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);
});
谢谢

最佳答案

如果您跟踪已发布的事件数量,您可以使用 skip :

  subscribe(next, error?, complete?) {
return this.mySubject.pipe(
skip(this.publishCount - 1)
).subscribe(next, error, complete);
}
这是 StackBlitz演示。

关于javascript - 让 ReplaySubject 只返回订阅的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67335771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com