Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto let ReactiveCommands observe their own IsExecuting observable

I have several commands in my ViewModel and I want to have the CanExecute of each button to be bound to an observable busy which is defined as none of the buttons is currently executing.

The following is what I came up with, but obviously it runs into a NullReferenceException.

busy = Observable.CombineLatest(this.PlayCommand.IsExecuting, this.PauseCommand.IsExecuting, (play, pause) => play && pause);

this.PauseCommand = new ReactiveCommand(busy.Select(b => !b));
this.PlayCommand = new ReactiveCommand(busy.Select(b=> !b));

Also the CanExecuteObservable property on ReactiveCommand is readonly, so I need to define an IObservable before I initialize the commands.

Any ideas on how to solve this chicken and egg problem? A better way of observing busy state for a ViewModel (or a collection of ViewModels) would be appreciated also :-)

like image 394
Wouter Avatar asked Apr 27 '14 11:04

Wouter


1 Answers

I would set up a proxy via using a Subject:

var areAllAvailable = new BehaviorSubject<bool>(true);

PauseCommand = new ReactiveCommand(areAllAvailable);
PlayCommand = new ReactiveCommand(areAllAvailable);

Observable.CombineLatest(PauseCommand.IsExecuting, PlayCommand.IsExecuting, 
    (pa,pl) => !(pa || pl))
    .Subscribe(allAreAvailable);
like image 83
Ana Betts Avatar answered Oct 14 '22 00:10

Ana Betts