While the below code works, I'm not sure it is the best practice. I'm wondering if I am over-thinking the situation.
Situation: The below code is in my main ViewModel constructor. The ViewModel has a property MessageHandler
that has a ReactiveCommand
property on it called ReceiveMessage
. The ViewModel has another property ScannerViewModel
with a RawMessage
Property on it. I would like to use the ReactiveUI .InvokeCommand()
extension method to pipe RawMessage
to ReceiveMessage
. I want this due to the convenience of it checking the .CanExecute
for me. This should happen even though MessageHandler
(or even ReceiveMessage
potentially) could change, as well as ScannerViewModel
.
this.WhenAnyValue(t => t.MessageHandler.ReceiveMessage)
.Select(cmd =>
this.WhenAnyValue(t => t.ScannerViewModel.RawMessage)
.InvokeCommand(cmd))
.Scan(Disposable.Empty,
(acc, n) =>
{
acc.Dispose();
return n;
})
.Subscribe();
So the above seems to work. I'm not too sure about whether or not I need to dispose the previous InvokeCommand
disposables as I go along, so maybe the .Scan
section is unneeded, or perhaps could be done better.
I tried the overload of the InvokeCommand
extension that lets you assign a target but it seemed to be static, or I could not figure out the syntax to make it take an Observable
as a target:
this.WhenAnyValue(t => t.ScannerViewModel.RawMessage)
.InvokeCommand(MessageHandler, m => m.ReceiveMessage);
That would follow the RawMessage
as its parent changed, but breaks if MessageHandler
changed. And this does not compile:
this.WhenAnyValue(t => t.ScannerViewModel.RawMessage)
.InvokeCommand(this.WhenAnyValue(t => t.MessageHandler), m => m.ReceiveMessage);
I'm not against keeping what I've got, unless someone finds a flaw with it. I am looking for something that is maybe a little less verbose and easier to follow.