Skip to content

Instantly share code, notes, and snippets.

@rarmatei
Last active October 22, 2017 20:18
Show Gist options
  • Save rarmatei/d91d2e5dc4f1e4a649ec0a508afb4711 to your computer and use it in GitHub Desktop.
Save rarmatei/d91d2e5dc4f1e4a649ec0a508afb4711 to your computer and use it in GitHub Desktop.
function delayedRefCount(delay) {
return (source) => {
let length = 0;
let timeout;
const onNewSubscriber = () => {
const onUnsubscribe = () => {
length--;
if (length === 0) {
timeout = setTimeout(() => {
source.connect().unsubscribe();
}, delay);
}
};
length++;
if (length === 1) {
source.connect();
}
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
return onUnsubscribe;
};
const obs = () => source;
return Rx.Observable.using(onNewSubscriber, obs);
};
}
const source = Rx.Observable
.interval(1000)
.do(x => console.log(x))
.take(10)
.publishReplay(1)
.let(delayedRefCount(3000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment