UNPKG

rxjs-loading-state

Version:

Eliminates manual state management for loading and error states by transforming Observables into a LoadingState

35 lines (34 loc) 1.27 kB
import { Observable } from "rxjs"; /** * Tracks an observable, by emitting loading events to the passed in state machine * @param {LoadingStateMachine<Data>} loadingStateMachine */ export function trackLoadingBy(loadingStateMachine, mapper = (v) => v) { return function (source) { return new Observable((subscriber) => { loadingStateMachine.start(); const innerSubscription = source.subscribe({ next: (value) => { loadingStateMachine.update(mapper(value)); subscriber.next(value); }, error: (error) => { loadingStateMachine.fail(error); subscriber.error(error); }, complete: () => { loadingStateMachine.succeed(loadingStateMachine.data); subscriber.complete(); }, }); const tearDown = () => { innerSubscription.unsubscribe(); // Reset to not-started if loading was cancelled if (loadingStateMachine.isLoading()) { loadingStateMachine.reset(); } }; return tearDown; }); }; }