Slide 1

Slide 1 text

Observables > Promises Everything is a stream Mark van Straten @markvanstraten

Slide 2

Slide 2 text

Sync Async Single Value Promise Multiple Array Observable

Slide 3

Slide 3 text

Observable Promise Lazy Eager Cancellable ✘ Chainable ✔ Testable ✔/✘ Time first class citizen ✘ Functional interface (map/filter) using Rx ✘ (does not exis

Slide 4

Slide 4 text

Observables all the way Gives you control over what happens when Rx.Observable.fromEvent(myContainer, 'mousemove') .map(evt => ({ X: evt.screenX, Y: evt.screenY })) .filter(coord => coord.X % 2 === 0) .debounceTime(100) .subscribe(console.log); https://jsbin.com/tarugak/edit?js,console,output

Slide 5

Slide 5 text

● Legacy code ● Interfacing with non-Observable libraries ● Ajax call to server (non cancellable) So when to use Promises?

Slide 6

Slide 6 text

Why not mix ‘n match? ● Control flow using Rx + Observables ● Promises for simple actions Rx.Observable.interval(1000) .mergeMap(_ => createAccountAndReturnPassword()) .take(3) .subscribe(console.log) function createAccountAndReturnPassword(){ // todo - create account in database return Promise.resolve(Math.random() .toString(36) .substring(7) ); }

Slide 7

Slide 7 text

Downside mix ‘n match ● How to test account create takes > 1 second? // promise + test + time? ● What if create account takes > 10 second? // promise + timeout ? ● What if it fails al together? // promise + retry logic? ● Cognitive overload // Is it a promise or an observable? (hint: flow/typescript)

Slide 8

Slide 8 text

Recap Go play with Rx // Observables Use Observables as your interface for async functions Internally use whatever you like (promise?) Wrap promises with Rx.Observable.defer() to make them lazy