import { Observable, Subscribable } from 'rxjs'; /** * Observable operator which calls the provided callbacks when observable * is subscribed to or unsubscribed from for the first time. * * Callbacks may be called multiple times if the last subscriber * is unsubscribed from it and then resubscribed again. * * @param onSubscribe - function which is called when observable * is subscribed to for the first time * @param onUnsubscribe - function which is called when the last subscriber * is unsubscribed from the observable */ export function onFirstSubscription( onSubscribe: (() => void) | undefined, onUnsubscribe: (() => void) | undefined ) { return (source: Subscribable) => { let count = 0; return new Observable((observer) => { if (count === 0) { onSubscribe?.(); } const sub = source.subscribe(observer); count++; return () => { sub.unsubscribe(); count--; if (count === 0) { onUnsubscribe?.(); } }; }); }; }