I've started playing around with the Reactive Extensions for .NET using the official beginner's guide, but a lot of the method overloads were not working for me (I've referenced System.Reactive). I am not sure whether that is because the how to guide is outdated or it has some other reason (if I'm missing some assemblies, pls tell me). Here is the original and altered code:
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Forms;
namespace RxFormsSandbox
{
class Program
{
static void Main(string[] arguments)
{
var textBox = new TextBox();
var form = new Form { Controls = { textBox } };
// MY CODE (WORKING)
var mouseMoves = Observable.FromEvent<MouseEventHandler, MouseEventArgs>(
handlerAction => (_, args) => handlerAction(args),
handler => form.MouseMove += handler,
handler => form.MouseMove -= handler);
var input = Observable.FromEvent<EventHandler, EventArgs>(
handlerAction => (_, args) => handlerAction(args),
handler => textBox.TextChanged += handler,
handler => textBox.TextChanged -= handler);
var mouseMovesSubscription = mouseMoves.Select(x => x.Location.ToString()).Subscribe(Console.WriteLine);
var inputSubscription = input.Subscribe(x => Console.WriteLine(textBox.Text)); // can I do this without directly accessing 'label' (via sender)
// END OF MY CODE
// ORIGINAL CODE AS PROVIDED IN THE SAMPLE
// var mouseMoves = Observable.FromEvent<MouseEventArgs>(form, "MouseMove");
// var input = Observable.FromEvent<MouseEventArgs>(textBox, "TextChanged");
//
// var mouseMovesSubscription = mouseMoves.Select(x => x.EventArgs.Location.ToString()).Subscribe(Console.WriteLine);
// var inputSubscription = input.Subscribe(x => Console.WriteLine(((TextBox)x.Sender).Text));
// END OF ORIGINAL SAMPLE CODE
using (new CompositeDisposable(mouseMovesSubscription, inputSubscription))
{
Application.Run(form);
}
}
}
}
With the premise, that the method's signatures has been indeed changed between releases, there are a couple of thing that bug me about my solution and I'd like to ask whether there is a better way:
- My rewritten version is significantly longer and I consider is less expressive. Is there a way to make it shorter (ideally without introducing magic strings)?
- input.Subscribe(x => Console.WriteLine(textBox.Text)); is not great, because it references outside code. I'd like to somehow access it via the 'sender' property.
My assembly comes from NuGet and its version is 1.0.10621.0.