Created
August 11, 2016 13:08
-
-
Save michaelneu/5d0fe265e6d80e1923fbb3c9eca4d30c to your computer and use it in GitHub Desktop.
Typescript implementation of a debouncer using rxjs Observable
This file contains 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 { Observable } from "rxjs/Observable"; | |
import { Observer } from "rxjs/Observer"; | |
import "rxjs/add/operator/debounceTime"; | |
/** | |
* Class representing a debouncer to delay incoming events. | |
*/ | |
export default class Debouncer<T> { | |
private observer: Observer<T>; | |
/** | |
* Creates a debouncer. | |
* | |
* @param {(data: T) => void} debounced The method to call when the event is debounced. | |
* @param {number} debounceTime The time to debounce the event. | |
*/ | |
public constructor(debounced: (data: T) => void, debounceTime: number) { | |
let observable = new Observable<T>((observer) => { | |
this.observer = observer; | |
}); | |
let subscription = observable.debounceTime(debounceTime).subscribe((data) => { | |
debounced(data); | |
}); | |
} | |
/** | |
* Update the debouncer's event's value. | |
* | |
* @param {T} data The value to assign to the debouncer. | |
*/ | |
public update(data: T) { | |
this.observer.next(data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment