有没有办法让条件限制。
我有一个类,它有一个带有2个参数的事件(控制发送者,字符串文本)。我想在我的Rx代码中使用这个事件,并使用限制。唯一的问题是我想限制文本,只针对同一个发件人。
因此,如果sender = textbox1,则节流300秒,但如果发件人更改,则忽略节流并在链中发送事件。
sender=textbox1, text = 'm' within 300 seconds (ignore)
sender textbox1, text = 'mu' within 300 seconds (ignore)
sender textbox1, text = 'muk' more than 300 seconds (process)
sender=textbox1, text = 'm' within 300 seconds(ignore)
sender=textbox2, text = 'y' within 300 seconds(process) //as the sender has changed now.
答案 0 :(得分:1)
以下代码将确保在显示值之前已经过了300ms,除非发件人已更改。
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
答案 1 :(得分:0)
这就是我为完成这项工作所做的工作
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();
var changedSender = source.Zip(source.Skip(1), (previous, next) => new { Previous = previous, Next = next }).DistinctUntilChanged(arg => arg.Next.Sender).Select(o => o.Previous).Publish().RefCount();
changedSender.Subscribe();
var either = changedSender.Merge(source.Throttle(TimeSpan.FromMilliseconds(300))); //.Do(o => Console.WriteLine("Do {0}", o.ToString()));
either.Subscribe(o => o.Print());
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("A", "bite1"));
source.OnNext(new Pair("A", "bite2"));
source.OnNext(new Pair("B", "a"));
source.OnNext(new Pair("B", "ani"));
source.OnNext(new Pair("B", "animal"));
System.Threading.Thread.Sleep(10);
source.OnNext(new Pair("A", "bitey"));
System.Threading.Thread.Sleep(500);
source.OnNext(new Pair("A", "at"));
source.OnNext(new Pair("B", "empty"));
source.OnNext(new Pair("A", "empty"));
source.OnNext(new Pair("C", "new"));
Console.ReadLine();