RxJS Observables, a gentle introduction.

Introduction

Anatomy of an Observable

  • Creating Observables
  • Subscribing to Observables
  • Executing the Observable
  • Disposing Observables

Creating Observables

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

Subscribing to Observables

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

Executing Observables

  1. next callback is used to process the emitted item.
  2. error callback is used to implement exception handling.
  3. complete callback is used to perform cleanup when the Observable is complete.
// 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();

--

--

--

Angular Developer | Angular Kenya Peer Mentor | Blogger | Aspiring Speaker

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is Koa.js?

Unit Testing 101

How convert Decimal number to Roman number.

How to Use NgRx Schematics and NgRx Entity to Speed Up Your Development Process

Prototypal Inheritance in Javascript

How to write readable JavaScript code

Leet Code — Roman to Integer

Git fetch & pull for all repos once

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
Job Alex Muturi

Job Alex Muturi

Angular Developer | Angular Kenya Peer Mentor | Blogger | Aspiring Speaker

More from Medium

My knowledge acquired about NGRX

Angular 14: The Latest & Top Features You Need To Know!

Creating my first app with Angular

Angular : Dynamically resolving service based on text/enum value