生成具有动态可变时间间隔的事件 [英] Generate events with dynamically changeable time interval

查看:30
本文介绍了生成具有动态可变时间间隔的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快速到达的数值流(亚毫秒),我想在屏幕上显示它们的即时值",出于可用性原因,我应该对该流进行下采样,更新最后一个值可配置时间间隔.该配置将根据用户偏好通过拖动滑块来完成.

I have a stream of numeric values that arrive at a fast rate (sub-millisecond), and I want to display their "instant value" on screen, and for usability reasons I should downsample that stream, updating the last value using a configurable time interval. That configuration would be done by user preference, via dragging a slider.

所以我想要做的是将源流的最后一个值存储在一个变量中,并有一个自动重新触发计时器,用该变量的值更新显示的值.

So what I want to do is to store the last value of the source stream in a variable, and have an auto-retriggering timer that updates the displayed value with that variable's value.

我考虑使用 RX,像这样:

I think about using RX, something like this:

Observable.FromEventPattern<double>(_source, "NewValue")
          .Sample(TimeSpan.FromMilliseconds(100))
          .Subscribe(ep => instantVariable = ep.EventArgs)

问题是,据我所知,我不能动态改变间隔.

The problem is that I cannot, as far as I know, dynamically change the interval.

我可以想象有很多方法可以使用计时器来实现,但我更喜欢使用 RX.

I can imagine there are ways to do it using timers, but I would prefer to use RX.

推荐答案

假设您可以将样本大小变化建模为可观察的,您可以这样做:

Assuming you can model the sample-size changes as an observable, you can do this:

IObservable<int> sampleSizeObservable;

var result = sampleSizeObservable
    .Select(i => Observable.FromEventPattern<double>(_source, "NewValue")
        .Sample(TimeSpan.FromMilliseconds(i))
    )
    .Switch();

Switch 基本上做你想做的,但是通过 Rx.它不会改变"间隔:Observables(通常)应该是不可变的.相反,每当样本大小发生变化时,它都会创建一个新的采样 observable,订阅新的 observable,放弃对旧的订阅,然后将这两个订阅合并在一起,这样对于客户端订阅者来说看起来是无缝的.

Switch basically does what you want, but via Rx. It doesn't "change" the interval: Observables are (generally) supposed to be immutable. Rather whenever the sample size changes, it creates a new sampling observable, subscribes to the new observable, drops the subscription to the old one, and melds those two subscriptions together so it looks seamless to a client subscriber.

这篇关于生成具有动态可变时间间隔的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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