Skip to content

Instantly share code, notes, and snippets.

@tw3
Last active July 9, 2020 11:52
Show Gist options
  • Save tw3/671c81861f7e91ca45dff1314f0d8549 to your computer and use it in GitHub Desktop.
Save tw3/671c81861f7e91ca45dff1314f0d8549 to your computer and use it in GitHub Desktop.
RxJS operator that keeps a running counter of the number of active requests
import { defer, Observable, ObservableInput } from 'rxjs';
import { finalize } from 'rxjs/operators';
/**
* This is an RxJS operator that keeps a running counter of the number of active requests.
* This can be used to show a spinner for the first of a series of requests, and hide the spinner
* once all requests in the series are complete.
*
* For example:
* const activeRequestMonitor: ActiveRequestMonitor = monitorActiveRequests({
* singleStartFn: () => this.showSpinner(),
* allCompleteFn: () => this.hideSpinner()
* });
* ...
* this.http.post(url1, body1).pipe(
* activeRequestMonitor
* ).subscribe(() => { ... })
* ...
* this.http.post(url2, body2).pipe(
* activeRequestMonitor
* ).subscribe(() => { ... })
*
*/
export const monitorActiveRequests = (config: ActiveRequestMonitorConfig): ActiveRequestMonitor => {
let numActiveRequests = 0;
return (source: Observable<any>) => {
return defer(() => {
numActiveRequests++;
if (config.singleStartFn) {
config.singleStartFn();
}
return source.pipe(
finalize(() => {
numActiveRequests--;
if (numActiveRequests === 0) {
if (config.allCompleteFn) {
config.allCompleteFn();
}
}
})
);
});
};
};
export interface ActiveRequestMonitorConfig {
singleStartFn: Function;
allCompleteFn: Function;
}
export type ActiveRequestMonitor = (Observable: any) => Observable<any>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment