如何在长时间运行的查询中间扩展Throttle Timespan?

Vek*_*ksi 2 c# reactive-programming system.reactive

是否可以在查询中间扩展Throttle Timespan值?例如,假设一个例子,如101 Rx Samples Throttle,就有这个查询var throttled = observable.Throttle(TimeSpan.FromMilliseconds(750));.

如果我想要改变它以便如果在前500毫秒期间将没有事件,那么对于之后的每个事件,节流值将被扩展到例如1500毫秒.

这是一个使用Switch运营商的地方吗?

Jam*_*rld 6

有一个重载Throttle接受一个工厂函数,它接受源事件并产生一个"节流",它是一个IObservable<T>(T可以是任何类型).事件将被抑制,直到节流流发出.

以下示例有一个每秒泵送一个流,一个油门工厂产生0.5秒的油门.因此,在开始时,源流不受限制.

如果输入say,2,油门将变为两秒油门,所有事件都将被抑制.更改为1,事件将再次出现.

void Main()
{
    var throttleDuration = TimeSpan.FromSeconds(0.5);
    Func<long, IObservable<long>> throttleFactory =
        _ => Observable.Timer(throttleDuration);

    var sequence = Observable.Interval(TimeSpan.FromSeconds(1))
                             .Throttle(throttleFactory);

    var subscription = sequence.Subscribe(Console.WriteLine);

    string input = null;
    Console.WriteLine("Enter throttle duration in seconds or q to quit");
    while(input != "q")
    {       
        input = Console.ReadLine().Trim().ToLowerInvariant();
        double duration;

        if(input == "q") break;
        if(!double.TryParse(input, out duration))
        {
            Console.WriteLine("Eh?");
            continue;
        }
        throttleDuration = TimeSpan.FromSeconds(duration);
    }

    subscription.Dispose();
    Console.WriteLine("Done");
}
Run Code Online (Sandbox Code Playgroud)

因为这是一个为每个事件生成油门的工厂函数,所以您可以创建更加动态的东西,根据特定的输入事件返回一个油门流.

作为这样的控制流的想法是在整个的Rx API用了一个很常见的技术,是非常值得周围包裹你的头:类似用途的例子包括other参数TakeUntil,在durationSelectorGroupByUntil,在bufferClosingSelectorBuffer.