Last active
October 22, 2017 20:18
-
-
Save rarmatei/d91d2e5dc4f1e4a649ec0a508afb4711 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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