RxJS Observables, a gentle introduction.

Introduction

Anatomy of an Observable

Subscribing to an Observable can be viewed to be the same as calling a Function.

Creating Observables

import { Observable } from 'rxjs';  const observable = new Observable ( function subscribe(subscriber){
subscriber.next('Hello World');
});
Observable.d.ts

Observables can be created with new Observable. Most commonly, observables are created using creation functions, like of, from, interval, etc.

Subscribing to Observables

observable.subscribe(x => console.log(x));

Subscribing to an Observable is like calling a function whilst providing callbacks where the data will be delivered to when the observable is executed.

Executing Observables

// Define an explicit observer (uncommon)
const observer = {
next: (res)=> console.log(`A response ${res} was emitted`),
error: (err) => console.log(`Error occurred: ${err}`),
complete: () => console.log(`No more response, yaaaa!`)
};
// Pass the Observer into the subscribe (uncommon)
const sub = observable.subscribe(observer);
//----------------------------------------------------------
// Or you can
// Pass the next callback function directly as the only function
const sub = observable.subscribe(
res => console.log(`A response ${res} was emitted`)
);
//----------------------------------------------------------
// Or you can
// Pass an Observer object
const sub = observable.subscribe({
next: (res)=> console.log(`A response ${res} was emitted`),
error: (err) => console.log(`Error occurred: ${err}`),
complete: () => console.log(`No more response, yaaaa!`)
});

Disposing Observables

const subscription = observable.subscribe(x => console.log(x));
const subscription = observable.subscribe(x => console.log(x)); // Cancel subscription
subscription.unsubscribe();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store