Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c# - Reactive Extensions for .NET (Rx): Take action once all events are completed

As a proof of concept, I want to write "Done" in a text box after a check box has been checked and a key has been pressed in a text box (in either order). I would expect this code to handle this, but it writes Done as soon as either event happens. Thanks for your help.

var seq = Observable.FromEvent<EventArgs>(this.checkBox, "CheckedChanged")
   .Merge(Observable.FromEvent<KeyPressEventArgs>(this.textBox, "KeyPress"));

seq.Subscribe((unused) => this.resultTextBox.Text = "Done");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Observable.When like so (I've added an additional CheckBox for this example):

var checkChanged  = Observable.FromEvent<EventArgs>(this.checkBox, "CheckedChanged");
var check1Changed = Observable.FromEvent<EventArgs>(this.checkBox1, "CheckedChanged");
var keyPress      = Observable.FromEvent<KeyPressEventArgs>(this.textBox, "KeyPress");

var plan1 = checkChanged
            .And(check1Changed).And(keyPress)
            .Then((cc, cc1, kp) => "Done.");

var when = Observable.When(plan1);

when.Subscribe((result) => this.resultTextBox.Text = result);

Also, if you can join other plans together, for example if things can be "done" when either one set of events fire, or also when another set of events fire:

var checkChanged  = Observable.FromEvent<EventArgs>(this.checkBox, "CheckedChanged");
var check1Changed = Observable.FromEvent<EventArgs>(this.checkBox1, "CheckedChanged");
var keyPress      = Observable.FromEvent<KeyPressEventArgs>(this.textBox, "KeyPress");
var keyPress1     = Observable.FromEvent<KeyPressEventArgs>(this.textBox1, "KeyPress");

var plan1 = checkChanged.And(check1Changed).And(keyPress).Then((cc, cc1, kp) => "Done.");
var plan2 = keyPress.And(keyPress1).Then((kp, kp1) => "Alternate done.");

var join = Observable.When(plan1, plan2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...