I am learning RXJS and have the following context:
Service:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, interval } from 'rxjs';
import { debounceTime, tap, debounce } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class SomeProvider {
private counter: BehaviorSubject<number> = new BehaviorSubject(0);
public counter$ = this.counter.asObservable() // .pipe(debounceTime(2000))
constructor(
) {
interval(1000).subscribe(value => {
console.log(value);
this.counter.next(value);
})
};
}
Component:
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { SomeProvider } from './some.service';
@Component({
selector: 'hello',
template: `<h1>{{ provider.counter$ | async }}</h1>`,
styles: [`h1 { font-family: Lato; }`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent {
constructor(public provider: SomeProvider) {
}
}
Here is the stackblitz: https://stackblitz.com/edit/angular-ivy-cdvwnj
So question - right now the component updates counter in the component's template every second. I would like to simply debounce it using debounceTime. I thought it will be as easy as adding a pipe to Observable with debounceTime operator. But if I uncomment that change - counter is not even there.
Question:
- how to apply debounceTime in this scenario correctly
- why if we add pipe with debounceTime async pipe inside the template stops working (and requires additional change detection)?