Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Observables > Promises

Observables > Promises

Short introduction of Observables ( + RxJs) given internally at my employer Q42

Mark van Straten

January 24, 2017
Tweet

More Decks by Mark van Straten

Other Decks in Programming

Transcript

  1. Observable Promise Lazy Eager Cancellable ✘ Chainable ✔ Testable ✔/✘

    Time first class citizen ✘ Functional interface (map/filter) using Rx ✘ (does not exis
  2. 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
  3. • Legacy code • Interfacing with non-Observable libraries • Ajax

    call to server (non cancellable) So when to use Promises?
  4. 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) ); }
  5. 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)
  6. 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