Learning Observable By Building Observable

Ben Lesh
Ben Lesh
Mar 8, 2016 · 6 min read

Observable is just a function that takes an observer and returns a function

Shape:

Purpose:

Basic Implementation:

function myObservable(observer) {
const datasource = new DataSource();
datasource.ondata = (e) => observer.next(e);
datasource.onerror = (err) => observer.error(err);
datasource.oncomplete = () => observer.complete();
return () => {
datasource.destroy();
};
}

Safe Observers: Make Observers Great Again

Observer Guarantees

function myObservable(observer) {
const safeObserver = new SafeObserver(observer);
const datasource = new DataSource();
datasource.ondata = (e) => safeObserver.next(e);
datasource.onerror = (err) => safeObserver.error(err);
datasource.oncomplete = () => safeObserver.complete();

safeObserver.unsub = () => {
datasource.destroy();
};

return safeObserver.unsubscribe.bind(safeObserver);
}

Designing Observable: Ergonomic Observer Safety

const myObservable = new Observable((observer) => {
const datasource = new DataSource();
datasource.ondata = (e) => observer.next(e);
datasource.onerror = (err) => observer.error(err);
datasource.oncomplete = () => observer.complete();
return () => {
datasource.destroy();
};
});

Operators: Also Just Functions

function map(source, project) {
return new Observable((observer) => {
const mapObserver = {
next: (x) => observer.next(project(x)),
error: (err) => observer.error(err),
complete: () => observer.complete()
};
return source.subscribe(mapObserver);
});
}

Designing Observable: Making Operator Chains Pretty

map(map(myObservable, (x) => x + 1), (x) => x + 2);
pipe(myObservable, map(x => x + 1), map(x => x + 2));
myObservable.map(x => x + 1).map(x => x + 2);
Observable.prototype.map = function (project) {
return new Observable((observer) => {
const mapObserver = {
next: (x) => observer.next(project(x)),
error: (err) => observer.error(err),
complete: () => observer.complete()
};
return this.subscribe(mapObserver);
});
};

TLDR: Observables are a function that take an observer and return a function

Thanks to Raquel Moss

Ben Lesh

Written by

Ben Lesh

RxJS Lead, Software Engineer at Google, RxWorkshop.com. Views are my own

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade