Last active
October 22, 2017 20:04
-
-
Save rarmatei/cffc325326b874c74953e202a48621ce 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) => { | |
const subscribeUpdates = new Subject(); | |
let trackerConnection; | |
let subscriptionTracker = subscribeUpdates.scan((total, change) => change + total, 0) | |
.switchMap(count => { | |
return count === 0 | |
? Observable.timer(delay) | |
.do(_ => source.connect().unsubscribe() || trackerConnection.unsubscribe()) | |
: Observable.never(); | |
}).publish(); | |
const onNewSubscriber = () => { | |
source.connect(); | |
trackerConnection = subscriptionTracker.connect(); | |
subscribeUpdates.next(1); | |
return function onUnsubscribe() { | |
subscribeUpdates.next(-1) | |
}; | |
}; | |
const observable = () => source; | |
return Observable.using(onNewSubscriber, observable); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment