Reactive-Extensions

JavaScript

Sam Baeck

  • What is RxJS?

  • Observables

  • Creating Observables

  • Operators

  • Hot vs cold

  • Subject

  • Timer

What is RxJS?

  • Reactive programming library for JS, based on the Reactive Extensions (Rx)
  • Based on events
  • Treats every source of data with the same computing model using the Observable => Stream
  • Used in Angular!

RxJS

  • Interact with a multitude of events
  • Write less code to do more
    => avoid the 'if this then that'
  • Promises have their limitations
  • At the end... it's easier to reason about

Angular 1

  • Promises are used for async
  • Used only in $http requests
  • Cannot be cancelled. Always resolves or rejects
  • Can only hold a single value and only be resolved or rejected once

Angular 2 => event-based

  • DOM events => click, input, scroll, ...
  • WebSockets
  • Animations
  • Requests
  • Routing
  • Forms
  • ...

Observables

  • Collection of values overtime => stream of data
  • Imagine multiple promises as arrays
  • Can be manipulated in similar ways as arrays
  • Often represented as a marble diagram
  • It lets us define things that need to be done once an event arrives

Terminology

  • The stream is called the Observable
  • Listening to a stream is Subscribing
  • To do so we need an Observer
  • The result of subscribing is a Subscription

Promises vs Observables

Listening to a promise

Subscribing to an Observable

myPromise.then(successFn, errorFn);
myObservable$.subscribe(nextFn, errorFn, completeFn);

Promises vs Observables

Cancelling a promise

Cancelling an Observable

let subscription = myObservable$.subscribe(nextFn, errorFn, completeFn);

subscription.unsubscribe();

You can't!

Creating an Observable

  • create
  • empty
  • from
  • fromEvent
  • timer
  • fromPromise
  • interval
  • range
  • throw
  • new Observable(...)

Observable.interval

let intervalObs$ = Rx.Observable.interval(1000);

Observable.of

let observable$ = Rx.Observable.of('a','b','c');

Observable recap

  • A set of any number of events over any number of time
  • You can provide three methods for every type of event as the subscribe parameters
  • Once you subscribe, you get a subscription which you can use to unsubscribe

There's more!

Rx operators

  • Methods on an observable to create new observables
  • Can be used to filter, combine, transform
  • Operators can be chained

Map operator

Filter operator

Switchmap operator

  • Used to combine different observables
  • Takes an observable as parameter and returns another observable, unsubscribing from the first one and subscribing to the new one

Hot

  • Not lazy

  • Multicast

  • Same producer for every subscription

  • Lazy
  • Unicast
  • New producer for every subscription

Cold

  • Observables where you can add values to the stream yourself

  • You can manage the producer of values

Subjects

DEMOTIME

Reactive Extensions

By Sam Baeck

Reactive Extensions

  • 85