Basic Understanding of RxJS

What is RxJS ?

But what does it mean ?

source: https://stock.adobe.com
Image source: https://stock.adobe.com

RxJS Terms

Observer / Subscriber:

  • The next bottle comes so that he can process it in whatever way he wants.
    [ next item process it: next() ]
  • If some bottle has a defect [ error occurred, handle it: error() ]
  • When all bottles has been completed [ complete, you’re done: complete() ]
const observer = {
next: bottle => console.log(`Bottle is emitted ${bottle}`);
error: err => console.log(`Error occurred: ${err}`);
complete: () => console.log(`No more bottles. Goodbye for the day!`);
};

Observable / Observable Stream

  • Synchronous — items are emitted to the stream immediately
  • Asynchronous — items are emitted at some future point in time
const bottleStream = new Observable (bottleObserver => {
bottleObserver.next(‘bottle 1’);
bottleObserver.next(‘bottle 2’);
bottleObserver.complete();
});
const sub = bottleStream.subscribe(observer);
  1. As we have subscribed to the observable, code in the constructor gets executed.
  2. It first calls next() on the observer, displaying the next method message in the console.
  3. It calls next() again, displaying a second message in the console.
  4. Lastly it calls the complete() method, stopping our stream and displaying our complete message.
const sub = bottleStream.subscribe({
next: bottle => console.log(`Bottle is emitted ${bottle}`);
error: err => console.log(`Error occurred: ${err}`);
complete: () => console.log(`No more bottles. Goodbye for the day!`);
});

Stop the stream:

  • Call observer’s complete() method.
  • Use completing operators like : of(), from().
  • If an observer throws an error, the stream will stop automatically.
  • By unsubscribing the subscription using unsubscribe method: sub.unsubscribe();

Creating observables:

  • of(): Creates an observable using a set of defined values.
    const bottleStream = of(‘bottle1’, ‘bottle2’);
  • from(): creates an observable from an array/other data structure.
    const bottleStream = from([‘bottle1’, ‘bottle2’]);
  • fromEvent(): Creates an observable with any DOM event.
    const source = fromEvent(document, ‘click’);

Operators

of(3, 2, 4).pipe(
map(val => val * 2),
tap(val => console.log(val)),
take(2)
).subscribe(console.log);

pipe():

map():

tap():

  1. Debugging
  2. Performing actions outside the flow of data that don’t modify the stream.

take():

  1. Taking a specified numbers of items.
  2. Limiting unlimited streams such as streams created by an ‘interval’ function.
  1. map: First 3 will be emitted and pass it to map function: 3 * 2 = 6.
  2. tap: The first tap logs it to the console. // 6
  3. take: will taken it as first time
  4. subscribe: logs 6 to the console. // 6
  5. map: Secondly 2 will be emitted, so 2 * 2 = 4.
  6. tap: The second tap logs it to the console. // 4
  7. take: will taken it as second time
  8. subscribe: logs 4 to the console. // 4
of(3, 2, 4).pipe(
map(val => val * 2),
tap(val => console.log(val)),
take(2)
).subscribe(console.log);
Output:
6
6
4
4

Error Handling

  1. Catch and Replace
  2. Catch and Rethrow

Catch and Replace:

const http$ = this.http.get<Bottle[]>(‘/api/bottlesDetail’);
http$
.pipe(
catchError(err => of([{id: 1, material: 'glass', color: 'red'}])
.subscribe(
res => console.log(‘HTTP response’, res),
err => console.log(‘HTTP Error’, err),
() => console.log(‘HTTP request completed.’)
);

Catch and Rethrow:

const http$this.http.get<Bottle[]>('/api/bottlesDetail');http$
.pipe(
map(res => res['payload']),
catchError(err => {
console.log('caught mapping error and rethrowing', err);
return throwError(err);
})
)

References:

--

--

--

JS | Angular | React | PWA

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

Recommended from Medium

What is Nock? and how can i test REST API Using Axios (JS)

Getting started with Deno.js

Getting Started with Deno Introduction image.

How we work: React Native slide charts

React Chronicles: I love you and I hate you

Typescript Enums and Polymorphism with Type Matching

A Simple Blog with GraphQL, Apollo, React Router & styled-components.

Weird parts in JavaScript — part 1

Long colorful lines of code on a computer screen

Angular Material — Part 3: Navigation (Menus, Sidenavs and Toolbars)

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
Anjali Tanpure

Anjali Tanpure

JS | Angular | React | PWA

More from Medium

CS373 Spring 2022: Sabeer Shahzad Week 9

Chapter 04- How Objects Behave

CHAPTER 09 : NUMBERS AND STATICS

Extra Strength Methods