问题描述
有没有办法有条件的油门.
Is there a way to have conditional throttle.
我有一个类,它有一个带有 2 个参数的事件(控制发送者,字符串文本).我想在我的 Rx 代码中使用这个事件,并使用限制.唯一的问题是我想限制文本,只针对同一个发件人.
I have a class which has an event with 2 parameters (control sender, string text).I would like to use this event in my Rx code, and use throttling. The only problem is that i would like to throttle text, only for the same sender.
因此,如果发件人 = textbox1,则限制 300 秒,但是如果发件人更改,则忽略限制并将事件发送到链中.
So if the sender = textbox1, then throttle for 300 seconds, however if the sender changes then ignore throttle and send the event up in the chain.
sender=textbox1, text = 'm' 300 秒内(忽略)
sender textbox1, text = 'mu' 300 秒内(忽略)
sender textbox1, text = 'muk' 超过300秒(进程)
sender=textbox1, text = 'm' 300 秒内(忽略)
sender=textbox2, text = 'y' in 300 seconds(process)//因为现在发件人已经改变了.
推荐答案
以下代码将确保在显示值之前已经过去了 300 毫秒,除非发送者已更改.
The following code will make sure that 300ms have passed before showing a value, unless the sender has changed.
var source = new Subject<Pair>();
// The Publish().RefCount() and Subscribe() are to make the sequence hot
var changedSender = source.DistinctUntilChanged(p => p.Sender).Publish().RefCount();
changedSender.Subscribe();
var throttled = source.Select(p =>
Observable.Amb(changedSender, source.Skip(TimeSpan.FromMilliseconds(300))).Take(1))
.Concat();
throttled.Subscribe(WritePair);
source.OnNext(new Pair("A", "i"));
System.Threading.Thread.Sleep(10);
source.OnNext(new Pair("A", "it"));
System.Threading.Thread.Sleep(10);
source.OnNext(new Pair("A", "bit"));
System.Threading.Thread.Sleep(500);
source.OnNext(new Pair("A", "bite"));
source.OnNext(new Pair("B", "a"));
System.Threading.Thread.Sleep(10);
source.OnNext(new Pair("A", "bitey"));
System.Threading.Thread.Sleep(500);
source.OnNext(new Pair("A", "at"));
这会产生以下输出:
A: bite
B: a
A: bitey
A: at
这篇关于Reactive.NET 条件限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!