For WPF programming there is a Reactive Extensions extension called ReactiveUI. I like the idea very much, but the last time I have looked at the online documentation, it was slightly out of sync with the current version, and the examples are slightly more elaborate than hello world. I’ll have to return to ReactiveUI at a later point in time.
As it seems, many people still use WinForms. A typical Forms application contains quite a number of event handlers. What Rx promises is a declarative design of your program (UI) logic. Without getting too concerned with lifetime management of this hello world example, here it is:
The first TextBox gets updated asynchronously with the current time, the second TextBox shows the word count of the text entered in the third TextBox. All that is defined in a single Load event handler, private void Form1_Load(…). You can get the code here.
The initialization of the logic (in Form1_Load) is as follows:
Update textBox1 with the current time asynchronously every second
Observable.Interval(TimeSpan.FromSeconds(1)) .ObserveOn(this) // scheduled on the Form's scheduler .Subscribe(_ => textBox1.Text = DateTime.Now.ToLongTimeString());
No threading code needed :).
Convert an event handler into an observable and set its registration
var textChanged = Observable.FromEventPattern<EventHandler, EventArgs> ( handler => handler.Invoke, h => textBox3.TextChanged+= h, h => textBox3.TextChanged-= h );
Subscribe to the textChanged observable in order to update the word count
textChanged .ObserveOn(this) // scheduled on the Form's scheduler .Subscribe(x => textBox2.Text = textBox3.Text .Split() .DefaultIfEmpty() .Where(s=>s.Trim().Length>0) .Count() .ToString());
That’s it. No other explicit event handlers, just these observables with lambdas.