In the body of my class, I have this line of code:
private ReactiveCommand<object> _displayCommand = ReactiveCommand.Create();
In the class constructor, I set up a subscription:
_displayCommand.Subscribe(_ =>
{
MessageBox.Show("Button clicked.");
});
Is it possible to write some sort of extension method to effectively combine these two commands into one, so with a single function call we can call both ReactiveCommand.Create(), and create a subscription using Reactive Extensions (RX)?
This would group all logically related code together, and make the ViewModel much cleaner.
Update
This is what I have so far (thanks to @jt000):
public static ReactiveCommand<object> CreateAndSubscribe(Func<object> fn)
{
var displayCommand = ReactiveCommand.Create();
displayCommand.Subscribe<object>(_ => fn.Invoke());
return displayCommand;
}
private ReactiveCommand<object> _displayCommand = CreateAndSubscribe(() =>
{
return MessageBox.Show("Hello");
});
public ReactiveCommand<object> DisplayCommand
{
get { return _displayCommand; }
protected set { _displayCommand = value; }
}
However, I need to occasionally insert the call .Buffer(TimeSpan.FromSeconds(1).
between displayCommand
and .Subscribe(fn)
, and this function is not generic enough to do that. What I really need is some way of passing the entire subscription in to CreateAndSubscribe
- perhaps some Func
that takes an IObservable
?
This means I could use something like the following function call:
private ReactiveCommand<object> _displayCommand =
CreateAndSubscribe(o => o.Subscribe(() =>
{
return MessageBox.Show("Hello");
}));
and if I wanted to insert .Buffer(TimeSpan.FromSeconds(1))
:
private ReactiveCommand<object> _displayCommand =
CreateAndSubscribe(o => o.Buffer(TimeSpan.FromSeconds(1)).Subscribe(() =>
{
return MessageBox.Show("Hello");
}));