在一个时间窗口中检测3个事件 [英] detecting 3 events in a time window

查看:67
本文介绍了在一个时间窗口中检测3个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是rx的新手,我正在试图弄清楚如何在6秒内检测到3个或更多事件发生。 我在网上搜索过,但找不到这样的例子。

I'm new to rx, and I'm trying to figure out how to detect if 3 or more event happen in a 6 seconds.  I've searched on line, but can't find an example like this.

我想我需要

var error = evts.Throttle( Timespan.FromSeconds(6))

var error = evts.Throttle(Timespan.FromSeconds(6))

提供窗口,但是如何检测触发器何时有3个或更多事件?

to provide the window, but how do I detect when trigs has 3 or more events ?

谢谢,

推荐答案

Kurt,

如果您正在寻找在一段时间内发生3个事件时只推送一个值的东西,您可以使用:

If you are looking for something that just pushes a value when 3 events within a period of time happen you could use this:

//Produces a value when any overlapping windows produce 3 events within 6 seconds
void Main()
{
	var source = Observable.Interval(TimeSpan.FromSeconds(1)).Take(6);
	
	var sharedSource = source.Publish();
	
	IObservable<Unit> excessEvents = sharedSource
		.Window(sharedSource, _=>Observable.Timer(TimeSpan.FromSeconds(6)))
		.Select(w=>w.Skip(2).Take(1).SelectMany(_=>Observable.Return(Unit.Default)))
		.SelectMany(x=>x);
	
		
	excessEvents.Dump();	//LinqPad operator to show results.
	sharedSource.Connect();
}

两个关键行是:

//Opens a new window every time a value from the 
// source is produced
//Holds the window open for 6 seconds
.Window(sharedSource, _=>Observable.Timer(TimeSpan.FromSeconds(6)))

//Given each window produced above, push a single value
// if the window has more than 2 values.
.Select(w=>w.Skip(2).Take(1).SelectMany(_=>Observable.Return(Unit.Default)))

我发布序列的原因是确保它是热门的(即我们不会产生任何订阅副作用)。这是专门完成的,因为我们将它用作windowOpenings序列。

The reason I publish the sequence is to ensure it is Hot (i.e. we don't incur any subscription side effects). This is done specifically because we use it as the windowOpenings sequence.

我对你要做的事情感兴趣,即这里更大的用例是什么?你想让序列返回3个事件吗?你想要所有的活动,但是当快速连续3发生时会出错吗?你想抑制发生得太快的
事件吗?

I am interested in what you are going to do with this, i.e. what is the larger use case here? Do you want the sequence to return the 3 events? Do you want all of the events, but to error when 3 happen in quick succession? Do you want to just suppress events that happen too quickly?

HTH

Lee Campbell

Lee Campbell


这篇关于在一个时间窗口中检测3个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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