Created
July 3, 2020 04:08
-
-
Save thaylongs/694b0645556911cd640b3e3d13a63c5c to your computer and use it in GitHub Desktop.
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, OnInit} from '@angular/core'; | |
import {BehaviorSubject, Observable, Subject, Subscription} from 'rxjs'; | |
import {filter, takeUntil} from 'rxjs/operators'; | |
export class GenericController implements OnDestroy, OnInit { | |
private unsubscribe$ = new Subject<void>(); | |
isLoadingAsync: Observable<boolean>; | |
/* Is loading */ | |
private isLoadingAsyncSubject = new BehaviorSubject(false); | |
private isLoadingBasicDataSubject = new BehaviorSubject(null); | |
private isLoadingBasicData: Observable<void>; | |
unsubscribeOnDestroy = <T>(value: Observable<T>): Observable<T> => value.pipe(takeUntil(this.unsubscribe$)); | |
constructor() { | |
this.isLoadingAsync = this.isLoadingAsyncSubject.asObservable(); | |
this.isLoadingBasicData = this.isLoadingBasicDataSubject.asObservable().pipe(filter(data => data != null && !data)); | |
} | |
get isLoading(): boolean { | |
return this.isLoadingAsyncSubject.value; | |
} | |
set isLoading(value: boolean) { | |
this.isLoadingAsyncSubject.next(value); | |
} | |
ngOnInit(): void { | |
this.isLoading = true; | |
const result = this.loadBasicData(); | |
this.isLoadingBasicDataSubject.next(true); | |
if (result) { | |
result.add(() => { | |
this.isLoadingBasicDataSubject.next(false); | |
this.isLoading = false; | |
}); | |
} else { | |
this.isLoadingBasicDataSubject.next(false); | |
this.isLoading = false; | |
} | |
} | |
ngOnDestroy() { | |
this.isLoadingBasicDataSubject.complete(); | |
this.isLoadingAsyncSubject.complete(); | |
this.unsubscribe$.next(); | |
this.unsubscribe$.complete(); | |
} | |
loadBasicData(): Subscription { | |
return null; | |
} | |
onLoadData(): Observable<void> { | |
return this.isLoadingBasicData; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment