I have an Observable that emits when the callback of an external api is invoked. I would like to skip(n) emissions where n is the amount of subscribers subscribed to the observable.
E.g.: Subscriber that subscribes 2nd should only receive second emission and then unsubscribe.
The skip operator does not work as the number of subscriptions may change.
https://stackblitz.com/edit/rxjs-qdnh9f
let toSkip = 0;
const source = () => {
return Observable.create((observer) => {
toSkip++;
// External API callback
const handler = (count) => () => {
observer.next(count++);
};
const interval = setInterval(handler(1), 1000)
const unsubscribe = () => {
toSkip--;
console.log('clear interval');
clearInterval(interval)
}
observer.add(unsubscribe);
}).pipe(
skip(toSkip),
take(1)
);
}
const subscription1 = source().subscribe(x => console.log('subscription1', x));
const subscription2 = source().subscribe(x => console.log('subscription2', x));
// subscription3 should emit "2" as subscription2 will unsubscribe never run
const subscription3 = source().subscribe(x => console.log('subscription3', x));
setTimeout(() => {
subscription2.unsubscribe();
}, 500);
Subscription3 should emit "2" as subscription2 will unsubscribe before called.
Expected output on the console:
clear interval
subscription1 1
clear interval
subscription3 2
clear interval