RxJs Observables

Reactive Javascript’s observables are similar to promises in that they both are an object that represents the eventual completion (or failure) of an asynchronous function. But in their execution, ability to handle multiple events, and features, observables have much more interesting functionality.

Set Up

// CDN <script src="https://npmcdn.com/@reactivex/rxjs@version/dist/global/Rx.umd.js"></script>
// in console
npm install rxjs-es
// in javascript
import { Observable} from 'rxjs/Observable'

Creation, Execution and Multiple Events

const simpleObs = Rx.Observable.create(callback)
const fromEvent = Rx.Observable.fromEvent(target, eventName)
const fromProm = Rx.Observable.fromPromise(promise)

In its simplest form, an observable is created by using the create method. Otherwise, there are a number of creation operators available here.

While promises use eager execution, observables use lazy execution. That is, rather than executing immediately, an observable will only execute when it is needed. Additionally, a promise can only be responsible for a single event, but an observable can handle zero or more.


Rx.Observable.fromEvent(target, 'keyup')
.subscribe(event => console.log(event.target)

In this case, the observable will keep track of every emission, but will only emit the most recent item after the set time span has passed without another emission.


Rx.Observable.fromEvent(target, 'mousemove')
.subscribe(event => console.log(event.x, event.y)

Like debouncing, throttling limits how often it can emit a value. It will keep collecting emissions, but will only emit once per the set time span.


let obs = Rx.Observable.create(callback)
// somewhere else 

You can cancel an observable by unsubscribing from it.

Error Handling

.catch(err => {
return Rx.Observable.fromPromise(fetch('https://good.api'))
.subscribe(res => console.log(res), err => console.log('error!'))

Error handling allows for you to set up a fallback option.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.