如何清理/清除 rxjs 中 SubjectReplay 实例的缓存? [英] How to clean/clear cache of a SubjectReplay instance in rxjs?

查看:42
本文介绍了如何清理/清除 rxjs 中 SubjectReplay 实例的缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SubjectReplay,我想将它重置为没有缓存值,所以在重置后下一个订阅者不会获得历史记录?

I have a SubjectReplay and I would like to reset it to no cache values so after this reset the next subscriber doesn't get the history?

示例

  • 新主题重播
  • subject.next(1)
  • 重置主题 <- 这个问题
  • subject.subscribe()//不应该收到 1

我该怎么做?我需要主题是同一个实例.

how can I do this? I need the subject to be the same instance.

推荐答案

对于您的要求,我想到的最佳方式

The best way that comes to my mind with your requirement

我需要主题是同一个实例

I need the subject to be the same instance

应该有以下可观察的:

// This is your input
const source$: Observable<T>;

const proxy$ = new ReplaySubject<T>(n);
const reset$ = new BehaviorSubject<number>(0);

现在重要的是,我们在 source$ 上发出之前连接以下内容:

Now it's important that we hook up the following before you emit on source$:

source$.pipe(timestamp()).subscribe(proxy$);

最后,您可以像这样公开您的数据:

Then, finally, you can expose your data like this:

const data$ = proxy$.pipe(
  withLatestFrom(reset$),
  filter(([timedItem, resetTimestamp]) => timedItem.timestamp > resetTimestamp),
  map(([timedItem]) => timedItem.value),
);

您现在可以使用 reset$.next(+new Date()) 来触发重置.

You can now use reset$.next(+new Date()) to trigger the reset.

如果您可以确保为 source$ 提供带时间戳的值,则可以跳过 proxy$.

If you can make sure to provide timestamped values to source$, you can skip the proxy$.

这篇关于如何清理/清除 rxjs 中 SubjectReplay 实例的缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆