Created
April 21, 2021 08:43
-
-
Save dmorosinotto/97b07a6ba43e6a6cd57bb18521268c01 to your computer and use it in GitHub Desktop.
Angular Pipe to transform value or value$ -> debounced (def 150ms) observable USAGE <cmp [prop]= "value | debounce | async"></cmp>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { OnDestroy, Pipe, PipeTransform } from '@angular/core'; | |
import { BehaviorSubject, Observable } from 'rxjs'; | |
import { debounceTime } from 'rxjs/operators'; | |
@Pipe({ name: 'debounce', pure: true }) | |
export class DebouncePipe implements PipeTransform, OnDestroy { | |
private _bs: BehaviorSubject<any>; | |
private _obs: Observable<any>; | |
private _old: any; | |
transform(value: Observable<any> | any, debounce: number = 150) { | |
if (this._old !== value) { | |
this._old = value; | |
if (value instanceof Observable) { | |
this.safeClearBS(); // DISTRUGGO L'EVENTUALE BehaviorSubject INTERNO NON MI SERVE PIU' | |
// SE MI ARRIVA UN OBSERVABLE, SEMPLICEMENTE GLI AGGANCERO' debounceTime | |
return (this._obs = value.pipe(debounceTime(debounce))); | |
} else { | |
// ALTRIMENTI SE MI ARRIVANO VALORI NORMALI (NON OBSERVABLE) ALLORA USO UN BehaviorSubject | |
// PER EMETTERE I VALORI CHE MI ARRIVANO E POI LO RITORNO COME OBSERVABLE + debounceTime | |
if (!this._bs) { | |
// SE E' IL PRIMO VALORE CHE ARRIVA CREO AL VOLO IL BehaviorSubject INTERNO | |
this._bs = new BehaviorSubject<any>(value); | |
} else { | |
// SE INVECE L'AVEVO GIA' CREATO SEMPLICEMENTE EMETTO IL VALORE CHE ARRIVA | |
this._bs.next(value); | |
} | |
// RITORNO SEMPRE UN OBSERVABLE CON debounceTime IN MODO DA IGNORARE CAMBIAMENTI VELOCI | |
return (this._obs = this._bs.pipe(debounceTime(debounce))); | |
} | |
} else { | |
// SE MI ARRIVA STESSO OGGETTO RITORNO VECCHIO OBSERVABLE GIA' CREATO CON debounceTime | |
return this._obs; | |
} | |
} | |
private safeClearBS() { | |
// COMPLETO IN MANIERA PULITA L'EVENTUALE BehaviorSubject INTERNO E POI LO DISTRUGGO | |
if (this._bs) { | |
this._bs.complete(); | |
this._bs = null; | |
} | |
this._obs = null; | |
this._old = undefined; | |
} | |
ngOnDestroy() { | |
this.safeClearBS(); | |
console.warn('DESTROY'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment