memory of a dream
memory of a dream

Reputation: 1267

Combine 2 reactive properties into a reactive command with Reactive Bindings

I'm new to this reactive extensions stuff but I see it has some really useful stuff.

One of the things I really like is the ability to turn a bool property into a command that executes on that condition.

For example if I model an interaction with a door I'll have in my view model something like this:

 public ReactiveProperty<bool> IsOpen{ get; }

and

 public ReactiveCommand<bool> SetIsLocked { get; }

then I can do something like this:

 this.SetIsLocked = this.IsOpen.Select(isOpen => !isOpen).ToReactiveCommand<bool>(); 
 this.SetIsLocked .Subscribe(isLocked => this.Door.IsLocked = isLocked );

This generates a command that will update it's CanExecute each time the IsOpen flag changes and will set the appropriate value on my door when called.

But what If I add another flag which is also a bool, saay something like this:

public ReactiveProperty<bool> HasLock{ get; } 

Now I want my command to execute if the door has a lock and is closed but I haven't found any way to do that.

Some of you may say that I can do that by creating another reactive property which kind of merges the two and I know I can make it work that way but what I want to know is if there's a way to do it by merging the IObservables and what would be the syntax for something like that.

Upvotes: 1

Views: 1060

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27871

I think you can use CombineLatest like this:

SetIsLocked =
    IsOpen
    .CombineLatest(
        HasLock,
        (open,has_lock) => !open && has_lock)
    .ToReactiveCommand<bool>();

Upvotes: 3

Related Questions