Let’s assume there is a service that exposes a startItUp():Observable<Graph> API endpoint. Whenever a consumer subscribes to this, a bunch of heavy requests are made to the server, and returned data is packaged for the subscriber.

What if we want to add some passive listeners to the above event? What if we want an API passiveState():Rx.Observable<Graph> that doesn’t trigger any of those heavy server requests, and instead waits patiently for somebody else to trigger them?

What if I wrote an actual example rather than asking all these nonsensical rhetorical questions:

  • Subscriber1 goes: service.passiveState().subscribe(x => ...)
  • Time passes and nothing happens…

Last time I published an investigation on RxJS Matthew Podwysocki gave me a one-line alternative to essentially my whole article:

So here’s hoping that somebody notices a ridiculously simple solution this time as well, as I’d be super interested!

Observables are great. You can share an underlying producer to multiple subscribers, and you can set it up with a refCount() so that it only initiates itself when it has at least 1 subscriber and then it tears itself down when it goes back down to 0 subscribers.

Imagine, however, that we have a very expensive observable (maybe a combineLatest() of…


In RxJS, there’s a startWith operator that emits the items you specify as arguments before it starts emitting from the source observable.

Recently, I’ve run across a use-case where I need to emit one final item before letting the observable complete: an endWith operator.

It would look like the below:

Rx.Observable
.interval(100)
.take(2)
.endWith(999)
.subscribe(
(x) => console.log(x),
(err) => console.error(err),
() => console.log("complete")
);
// Will log:
// 0
// 1
// 999
// complete

And to get straight to the point, here’s the implementation I came up with:

Rx.Observable.prototype.endWith = function(finalValue) { return new Rx.Observable((observer) => { const…

Rares Matei

Front-end developer with special interest in Angular/JavaScript/TypeScript/RxJS, mentor at @CodeYourFuture_ & CodeClubPro.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store