[英]Use Observable.FromEventPattern to perform action after inactivity or count
I have an observable stream created from an event pattern like seen below. 我有一个可观察的流,它是从事件模式创建的,如下所示。
var keyspaceStream = Observable.FromEventPattern<RedisSubscriptionReceivedEventArgs>(
h => keyspaceMonitor.KeySpaceChanged += h,
h => keyspaceMonitor.KeySpaceChanged -= h);
What I want to do is subscribe to the stream and execute a method when there has either been 10 seconds of inactivity (no events have occurred) or 100 events have fired without the method having been executed. 我想要做的是订阅流并执行一个方法,当有10秒的不活动(没有发生事件)或100个事件已经触发而没有执行该方法。 This is to avoid scenarios when events are fired every 5 seconds and the onNext method is never called.
这是为了避免每隔5秒触发事件并且从不调用onNext方法的情况。
How can I accomplish this? 我怎么能做到这一点? I know how to do the first part (see below) but I can't figure out how to do the counting logic.
我知道如何做第一部分(见下文),但我无法弄清楚如何进行计数逻辑。 Note that I already know how to subscribe to the stream.
请注意,我已经知道如何订阅流。
var throttledStream = keyspaceStream.Throttle(TimeSpan.FromSeconds(10));
Any help would be much appreciated! 任何帮助将非常感激! Thank you.
谢谢。
Use Buffer
with a custom bufferClosingSelector
. 将
Buffer
与自定义bufferClosingSelector
。 The idea here is that every buffer should be closed either after maxDuration
or after maxCount
items, whichever comes sooner. 这里的想法是每个缓冲区应该在
maxDuration
之后或maxCount
项之后maxCount
,以较早者为准。 Each time a buffer closes, a new one is opened. 每次缓冲区关闭时,都会打开一个新缓冲区。
var maxDuration = TimeSpan.FromSeconds(10);
var maxCount = 100;
var throttledStream = keyspaceStream.Publish(o =>
{
var reachedMaxDuration = o
.Select(_ => Observable.Timer(maxDuration, scheduler))
.Switch();
return o.Buffer(() => o
.TakeUntil(reachedMaxDuration)
.Take(maxCount)
.LastOrDefaultAsync());
});
I assume you provide the IScheduler scheduler
. 我假设您提供
IScheduler scheduler
。 The type of throttledStream
will be IObservable<IList<EventPattern<RedisSubscriptionReceivedEventArgs>>>
. throttledStream
的类型将是IObservable<IList<EventPattern<RedisSubscriptionReceivedEventArgs>>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.