Last active
February 14, 2019 13:15
-
-
Save kosich/4a7415f3528aa125fb686204041138cb to your computer and use it in GitHub Desktop.
Observable that tracks its observers count. Run at https://observable-playground.github.io/gist/4a7415f3528aa125fb686204041138cb
This file contains 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
const { chart } = require('rp-api'); | |
const { Observable, timer, merge } = require('rxjs'); | |
const { take } = require('rxjs/operators'); | |
function createTrackedObservable(onEmpty) { | |
let count = 0; | |
return new Observable(() => { | |
count++; | |
return ()=>{ | |
count--; | |
if (count === 0 && onEmpty) { | |
onEmpty(); | |
} | |
}; | |
}); | |
} | |
console.log('Start'); | |
const onEmpty = () => console.log('Done'); | |
const source$ = createTrackedObservable(onEmpty); | |
const timer$ = timer(0, 5); | |
const tracked$ = merge(source$, timer$); | |
tracked$ | |
.pipe(take(5)) | |
.subscribe(chart.createRxObserver()); | |
setTimeout(()=>{ | |
tracked$ | |
.pipe(take(2)) | |
.subscribe(chart.createRxObserver()); | |
}, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment