【问题标题】:how can i throttle a stream of values added to a BehaviourSubject stream with next?如何使用 next 限制添加到 BehaviorSubject 流中的值流?
【发布时间】:2020-04-14 16:50:44
【问题描述】:

从一个空的 observable 开始,我有源源不断的非 rxjs 事件流,我需要使用 rxjs 对其进行节流,但我找不到创建节流输出的方法。在我的用例中,我不知道第一个值何时到达,也无法确定新值到达的频率。

https://stackblitz.com/edit/rxjs-behaviorsubject-simpleexample-etebvz?file=index.ts

我希望这个示例能够工作并显示使用 next() 添加的值以 1 秒间隔显示,但它不起作用。

import { BehaviorSubject, interval } from 'rxjs';
import { tap, map, throttle } from 'rxjs/operators';

const subject = new BehaviorSubject(1);
const example = subject.pipe(
  throttle(ev => interval(1000)),
  tap((ev) => console.log(ev))
)

example.subscribe();

example.next(2);
example.next(3);
example.next(4);
example.next(5);
example.next(6);

我找不到任何在线示例来匹配这个(显然)简单的用例,并且使用 rxjs 来实现这一点感觉不直观。任何帮助深表感谢。

【问题讨论】:

    标签: rxjs throttling


    【解决方案1】:

    throttleTime 允许您指定在再次发射之前要等待的毫秒数。

    const example = subject.pipe(
      throttleTime(1000),
      tap((ev) => console.log(ev))
    )
    

    Stackblitz

    我建议查看operator decision tree 并点击查看可用的选项:

    我有一个现有的 Observable

    我想忽略值

    频繁发生

    【讨论】:

    • 您好,谢谢您的回答。如果我不介意丢失使用 .next() 添加的项目,有没有办法使用throttle() 实现类似的解决方案?我不想在流中引入人为延迟,只需将输出调整为定期间隔。
    • @LaurenceFass 抱歉,我以为您想要在发射之间延迟 1 秒。我已经更新了答案。
    • 感谢您的帮助。回答的问题。 +1 决策树没有看到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多