Skip to content

Instantly share code, notes, and snippets.

@jhusain
Created May 4, 2017 00:26
Show Gist options
  • Save jhusain/a7f4ca2ed5491d0b92a3be1783b8377c to your computer and use it in GitHub Desktop.
Save jhusain/a7f4ca2ed5491d0b92a3be1783b8377c to your computer and use it in GitHub Desktop.
Observable implementation which optimizes very well in prepack
function Observable(subscribe) {
this._subscribe = subscribe;
}
const of = (v) => new Observable(observer => {
return observer.next(v);
});
Observable.prototype = {
map(f) {
return new Observable((observer) => {
return this.subscribe({
next: (v) => observer.next(f(v))
});
});
},
filter(f) {
return new Observable((observer) => {
return this.subscribe({
next: (v) => {
if (f(v)) {
observer.next(v);
}
}
});
});
},
flatMap(f) {
return new Observable((observer) => {
return this.subscribe({
next(v) {
const otherObs = f(v);
otherObs.subscribe(observer);
}
});
});
},
subscribe(observer) {
return this._subscribe(observer);
}
};
of(Math.random()).
flatMap((v) => of(Math.random())).
map((v) => v * Math.random()).
subscribe({
next: (v) => console.log(v)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment