Search code examples
c#validationreactiveuiavalonia

Delay ReactiveUI validation after typing


I want to check if the typed username already exists in the database. I've got an async query, but i don't want to check it after every typed character but 1s after typing finished.

Here is what i've got so far:

[Reactive]
public string? Username{ get; set; }

[ObservableAsProperty]
public bool IsUsernameExists{ get; }
...
this.WhenAnyValue(x => x.Username)
.Throttle(TimeSpan.FromMilliseconds(1000))
.Select(x => this.UserNameExists.ExecuteAsync(x))
.Select(x => x.Result)
.ToPropertyEx(this, vm => vm.IsUsernameExists);

this.ValidationRule(x => x.Username, x => !this.IsUsernameExists, "Username already exists.");

The problem is, when Username changed, the validation evaluates IsUsernameExists before it is updated because of the delay. So the validation is always 1 character behind typing. Does anyone know a solution for the problem?

Thanks in advance, Imre Horvath


Solution

  • I've got it working:

            this.ValidationRule(
                vm => vm.Name,
                this.WhenAnyValue(x => x.Name)
                .Throttle(TimeSpan.FromSeconds(0.7), RxApp.TaskpoolScheduler)
                .SelectMany(async x => (await this.BankNameExists.ExecuteAsync(x)) == true ?
                new ValidationState(false, "Name already exists.") : ValidationState.Valid)
                .ObserveOn(RxApp.MainThreadScheduler));