Skip to content

Instantly share code, notes, and snippets.

@foxel
Created March 2, 2018 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxel/d44a774cbfd3de1d11e7db4a2c9de327 to your computer and use it in GitHub Desktop.
Save foxel/d44a774cbfd3de1d11e7db4a2c9de327 to your computer and use it in GitHub Desktop.
Reactive loader with guarantee of no load collisions and loading status provided.
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/switchMap';
export class ReactiveLoader<T, T1> {
private _requestQueue: Subject<T1>;
private _resultQueue: Observable<T>;
private _loaded: boolean = false;
constructor(loaderFunction: (T1) => Observable<T>, initiallyLoaded: boolean = false) {
this._loaded = initiallyLoaded;
this._requestQueue = new Subject<T1>();
this._resultQueue = this._requestQueue.switchMap(_ => {
this._loaded = false;
return loaderFunction(_);
}).map(_ => {
this._loaded = true;
return _;
});
}
public load(arg?: T1): void {
this._requestQueue.next(arg);
}
public subscribe(next: (T) => any): Subscription {
return this._resultQueue.subscribe(next);
}
public complete() {
this._requestQueue.complete();
}
get loaded(): boolean {
return this._loaded;
}
get value(): Observable<T> {
return this._resultQueue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment