Skip to content

Instantly share code, notes, and snippets.

@kosich
Last active February 14, 2019 13:15
Show Gist options
  • Save kosich/4a7415f3528aa125fb686204041138cb to your computer and use it in GitHub Desktop.
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
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