bogdan.sachkovskyi
bogdan.sachkovskyi

Reputation: 86

ReactiveUI ReactiveCommand canExecute using Subject<bool> not working

I am using reactive ui in WPF application. There is base class for validation:

public abstract class ReactiveValidatingScreen : ReactiveScreen
{
    public Subject<bool> ValidationObservable { get; } = new Subject<bool>();

    private void Validate(string propertyName)
    {
        // ... some logic
        var isValid = GetValidationResult();
        ValidationObservable.OnNext(isValid);
    }
}

And view model:

public sealed class UserLoginViewModel : ReactiveValidatingScreen
{
    public UserLoginViewModel()
    {
        Login = ReactiveCommand.CreateAsyncTask(ValidationObservable, x => LoginImpl());
    }
}

My login button always disabled, while there is a call:

ValidationObservable.OnNext(true);

when validation passed.

But if I change to:

public sealed class UserLoginViewModel : ReactiveValidatingScreen
{
    public UserLoginViewModel()
    {
        var canLogin = this.WhenAnyValue(x => x.UserName, x => !string.IsNullOrEmpty(x) && x.Length == 3);
        Login = ReactiveCommand.CreateAsyncTask(canLogin, x => LoginImpl());
    }
}

It working fine, as expected.

ReactiveUI version - 6.5.0

Upvotes: 2

Views: 1087

Answers (1)

Gluck
Gluck

Reputation: 2962

ReactiveCommand will subscribe lazily to the given canExecute observable, in your case a possible explanation would be that your Validate call is done too early and OnNext performed before the command is bound.

Try with a ReplaySubject (or BehaviorSubject) instead.

Upvotes: 4

Related Questions