Created
March 2, 2018 06:48
-
-
Save foxel/d44a774cbfd3de1d11e7db4a2c9de327 to your computer and use it in GitHub Desktop.
Reactive loader with guarantee of no load collisions and loading status provided.
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 { 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