我以150-200次更新/秒的速度获得更新事件。我想把它与每把钥匙混合1秒钟。
示例:在1秒内,我按以下顺序接收3个按键A,B,C的更新:A1,B1,C1,A2,A3,B2
我想每1秒处理一次此更新&仅处理A3,B2&以上例子中的C1。
如何使用Reactive扩展程序解决此问题? 到目前为止我试过了:
Observable.FromEventPattern<EventArgs>(_listener, "EventHandler", System.Reactive.Concurrency.NewThreadScheduler.Default)
.GroupBy(x => x.EventArgs.Key)
.Subscribe(g =>
{
g.Sample(TimeSpan.FromSeconds(1))
.Subscribe(x1 =>
{
updateSubject.OnNext(key);
});
});
当然不是我所期待的。请为此建议正确的方法。
答案 0 :(得分:1)
你想要的是更像这样的东西:
getPendingIntent
但是,在Observable
.FromEventPattern<EventArgs>(_listener, "EventHandler", System.Reactive.Concurrency.NewThreadScheduler.Default)
.GroupBy(x => x.EventArgs.Key)
.Select(g => g.Sample(TimeSpan.FromSeconds(1.0)))
.Merge()
.Subscribe(x =>
{
updateSubject.OnNext(key);
});
内加updateSubject.OnNext(key);
是一个非常糟糕的主意。你真的应该展示更多你的代码,以便我们可以建议如何正确处理它。
答案 1 :(得分:1)
在那之后我没有做太多的事情
.format('hh:mm:ss', { trim: false })
合并没有为我做,但我尝试了:
Observable.FromEventPattern<EventArgs>(_listener, "EventHandler", System.Reactive.Concurrency.NewThreadScheduler.Default)
.GroupBy(x => x.EventArgs.Key)
.Subscribe(g =>
{
g.Sample(TimeSpan.FromSeconds(1))
.Subscribe(x1 =>
{
updateSubject.OnNext(key);
});
});
updateSubject
.SubscribeOn(NewThreadScheduler.Default)
.ObserveOn(NewThreadScheduler.Default)
.Subscribe(EventHandler); //Event Handler is the what gets called to handle the events
不确定我是否就在这里。
答案 2 :(得分:0)
这是一个自定义的 SampleLatestByKey
运算符,它可能可以满足您的需求:
/// <summary>
/// Samples a sequence of key-bearing elements at a specific interval. Upon each
/// sampling tick an IDictionary<TKey, TSource> is emitted, containing the latest
/// values that were emitted by each key during the last sampling period.
/// </summary>
public static IObservable<IDictionary<TKey, TSource>> SampleLatestByKey<TSource, TKey>(
this IObservable<TSource> source,
Func<TSource, TKey> keySelector,
TimeSpan interval,
IEqualityComparer<TKey> keyComparer = default)
{
return source
.Window(interval)
.SelectMany(window => window
.Aggregate(new Dictionary<TKey, TSource>(keyComparer),
(dict, x) => { dict[keySelector(x)] = x; return dict; }));
}
用法示例:
Observable
.FromEventPattern<EventArgs>(_listener, "EventHandler")
.SampleLatestByKey(x => x.EventArgs.Key, TimeSpan.FromSeconds(1.0))
.Subscribe(dict => dict.Keys.ToObservable().Subscribe(updateSubject));
this 问题中存在名为 SampleByKey
的类似自定义运算符。这两个运算符之间的区别在于 SampleByKey
在可观察序列的整个生命周期内为每个键发出最新值。 SampleLatestByKey
仅传播在上次采样间隔期间发出的值。