mr__brainwash
mr__brainwash

Reputation: 1382

RxJS debounceTime(0) still postpones execution

I am using Angular 7 and latest RxJS and ngrx/store. I faced a problem with debounceTime(0). debounceTime is an @Input() property of ui-input component. Its default value is 0. I want a possibility to use debounceTime for some inputs - for others - no. The input value I am getting from the store. Also, I have a validation service that should validate input values. I pass the input value to validation service through the selector. The problem is that in validation service I am getting previous values. Here is a simplified (updated) example. I have validation rule: input.length > 2. I want to get an error when the length is more than 2. But with debounceTime(0) I am getting a validation error in the console only when the length of the input is 4.

If I remove debounceTime - everything work as expected. I am getting a synchronous call:

How I can fix the problem? I didn't find any variants for applying debounceTime conditionally. Also, I think that something like this is not a good solution:

ngOnInit() {
    if (this.debounceTime > 0) {
      this._valueChanged
        .pipe(
          debounceTime(this.debounceTime),
        )
        .subscribe(value => this.inputted.emit(value));
    } else {
      this._valueChanged
        .subscribe(value => this.inputted.emit(value));
    }
  }

Upvotes: 3

Views: 3254

Answers (2)

mr__brainwash
mr__brainwash

Reputation: 1382

The answer to my question is to move the validation call in the same place as (inputted) event - onInit:

ngOnInit() {
    this._valueChanged
      .pipe(
        debounceTime(this.debounceTime),
      )
      .subscribe(value => {
        this.inputted.emit(value);
        const isValid = this.valdiationService.validate('myInput');
        if (isValid) {
          console.error('Input is not valid');
        }
      });
  }

Upvotes: 1

Sunil
Sunil

Reputation: 11243

You should not get the value from the Subject or BehaviorSubject instead you should subscribe on it.

store.service.ts

So following code should be changed

  process() {
    console.log('Store:   ', this.value$.getValue());
  }

to

 constructor(){
    this.value$.subscribe(v=>{
      console.log('Store:   ', v);
    })
  }

You don't need to call the store function manually, so you can remove that too.

Working sample code is here - https://stackblitz.com/edit/angular-5ajqn9

Upvotes: 0

Related Questions