live.pipe.ts
TypeScript source for Automatic loading spinners in Angular, 70 lines. Raw file
import { ChangeDetectorRef, OnDestroy, Optional, Pipe, PipeTransform } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { LoadingManager } from './loading-manager';
// stream$ | live returns the latest value from any observable, such as a WebSocket, undefined until the
// first one, and tells the nearest loader around it that it's loading until that first value arrives
@Pipe({ name: 'live', pure: false })
export class LivePipe implements PipeTransform, OnDestroy {
private source: Observable<any> | undefined;
private value: any;
private subscription: Subscription | undefined;
constructor(
private changeDetector: ChangeDetectorRef,
@Optional() private manager: LoadingManager,
) {
if (this.manager) {
this.manager.register(this);
}
}
transform(source: Observable<any> | undefined): any {
// Called on every change detection, so only subscribe when the observable changes
if (source !== this.source) {
this.source = source;
this.listen(source);
}
return this.value;
}
private listen(source: Observable<any> | undefined) {
// Stop listening to the last observable
this.stop();
if (source === undefined) {
return;
}
this.setLoading(true);
this.subscription = source.subscribe(
(value) => {
this.value = value;
this.setLoading(false);
this.changeDetector.markForCheck();
},
() => {
this.setLoading(false);
},
);
}
private setLoading(loading: boolean) {
if (this.manager) {
this.manager.setLoading(this, loading);
}
}
private stop() {
if (this.subscription !== undefined) {
this.subscription.unsubscribe();
this.subscription = undefined;
this.setLoading(false);
}
}
ngOnDestroy() {
this.stop();
if (this.manager) {
this.manager.unregister(this);
}
}
}