【问题标题】:Difference between sample and throttle in rxjsrxjs中sample和throttle之间的区别
【发布时间】:2018-06-11 17:38:47
【问题描述】:

我认为我无法正确理解 samplethrottle 之间的区别。

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-sample

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-throttle

它们都用于使 observable 静音。示例使用notifier 发出值,并且throttle 使用函数来确定它应该忽略值多长时间?

对吗?

【问题讨论】:

    标签: angular rxjs reactive-programming angular2-observables


    【解决方案1】:

    在下面的例子中:

    //emit value every 1 second
    const source = Rx.Observable.interval(1000);
    

    油门:

    //throttle for 2 seconds, emit latest value
    const throttle = source.throttle(val => Rx.Observable.interval(2000));
    //output: 0...3...6...9
    throttle.subscribe(val => console.log(val));
    

    示例:

    //sample last emitted value from source every 2s 
    const sample = source.sample(Rx.Observable.interval(2000));
    //output: 2..4..6..8..
    sample.subscribe(val => console.log(val));
    

    如您所见,Sample 拾取了最新发出的事件 (0, 2,...),而 Throttle 关闭了流 2 秒并等待下一个发出 (0, 3, 6,...)。

    【讨论】:

    • 这个站点使用了一种非常有用的 ascii 图表技术。我想看看这个例子的样子。见gist.github.com/staltz/868e7e9bc2a7b8c1f754。它基本上显示了一条数据线,然后是转换线,然后是转换后的数据线。 (以防链接停止工作)。寻找 clickStream.map(f).scan(g)。
    • 这样想,样本向后看,总能得到一些东西,而油门向前看,并在允许的时间窗口之后获得下一个事件。
    【解决方案2】:

    Throttle 忽略时间间隔内的所有事件。因此,如果您的通知程序发出事件,则源中的所有先前事件都将被忽略(并删除)。

    Sample 返回自上次采样以来的最后一个事件。因此,如果通知器发出一个事件,它将从源事件中查找上次采样的最新事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 2020-09-14
      • 2021-05-07
      • 2018-12-18
      • 1970-01-01
      • 2019-04-01
      相关资源
      最近更新 更多