loading...

Get start with Rxjs

danywalls profile image Dany Paredes ・4 min read

I'm starting to learn the rxjs library, Reactivex is an API for work with an asynchronous stream of data.

Rxjs help us handle changes in UI or domain events. We can use it for mouse move, button click, or domain events like when a property or collection updated his value.

Rxjs has 3 main pillars:

  • The Observer Pattern.
  • The Iterator Pattern.
  • Functional Programming.

Observer pattern

The observer pattern help to define dependency from one to many objects and when it changes his state, it notifies all objects related to him.

For example, a TV channel emits a movie, TVs can start a subscription to get the movie.

The channel should stop emit and every TV with an open subscription gets the notification or the TVs can unsubscribe.

Iterator pattern

It helps to define a set of methods to be able to access sequentially from a data collection.

Using functions to get data sequential, for a move between the data.

Functions like the next, last, or current object, moving between sequential.

Functional Programming.

The functional programming to create pure functions without data modified or his state.

The functions set of function and with a specific goal, without side effect or mutate our data. In a short story,

  • The Observer helps us notify changes.
  • The Iterator helps to move around the data sequentially.
  • Functional programming help works with the data without mutating it.

Setup a development environment.

I'm using parcel as a bundler it helps to set up easy and fast for development. Create a directory for the project rxjs-day-1, start npn init, and install parcel.

mkdir rxjs-day-1
cd rxjs-day-1
npm init --y
npm install -g parcel-bundler

Create an index.html and edit package.json and into scripts area define new for our index.html page.

"dev": "parcel index.html"

Create the app.ts file and import it into the HTML. Parcel understands the index contains a typescript file to handle it.

    <title>Document</title>
    <script src="app.ts"></script>

Install rxjs.

npm install rxjs

Run the parcel with npm run dev and we are ready for coding!

dany@dany-ibm:~/Desktop/learn-rxjs-day-1$ npm run dev

> learn-rxjs-day-1@1.0.0 dev /home/dany/Desktop/learn-rxjs-day-1
> parcel index.html

Server running at http://localhost:1234 
✨  Built-in 1.04s.

Create my first Observable.

I will create an observable, it will emit the list of lottery numbers for each one of them.

The Observable expect a Subscriber object. It provides functions like next for emitting or complete to stop emit values.

Open app.ts and import Observable from rxjs. Define a new const using the keyword new for the Observable with the subscriber as a parameter.

Into the body of the observable, define an array with the numbers. Using the map array method it calls the suscriber.next(value) and sends every value from the array.

Read more about observable in https://rxjs-dev.firebaseapp.com/guide/observable

import { Observable } from 'rxjs';

const LoteryChannel$ = new Observable((suscriber) => {
  const loteryNumber = [12, 11, 48, 38];
  loteryNumber.map((n) => suscriber.next(n));
});

Run your code en the browser http://localhost:1234, DAMM!!! nothing in the console, it is because the observable requires a subscription active.

Create a subscription

The subscription is create using the subscribe method from observable and return a subscription object.

const tv1 = LoteryChannel$.subscribe((value) => console.log(`tv1 ${value}`));

The tv1 subscription gets the values and prints it into the console.

Open the browser http://localhost:1234 and see the numbers in the console.

Create other subscription but with 5 seconds delay, using setTimeout, and when our subscription starts it get the same values like tv1.

setTimeout(() => {
  const tv2 = LoteryChannel$.subscribe((value) => {
    console.log(`tv2 ${value}`);
  });
}, 5000);

Read more about subscriptions
https://rxjs-dev.firebaseapp.com/guide/subscription

Unsubscribe and Complete.

The observable has an option to stop emitting data or the subscriptions want to not get more data from our "stream".

The Subscription stop gets data from the observable using the function unsubscribe.

const CNNChannel$ = new Observable((sus) => {
  const loteryNumber = [12, 11, 48, 38];
  sus.next("Number starts in 2 seconds");
  setTimeout(() => {
    loteryNumber.map((n) => sus.next(n));
  }, 2000);
});

const tv1 = CNNChannel$.subscribe((value) => console.log(`tv1 ${value}`));
const tv2 = CNNChannel$.subscribe((value) => console.log(`tv2 ${value}`));
setTimeout(() => {
  console.log("tv2 turnoff");
  tv1.unsubscribe();
}, 1000);

If the subscriber calls the complete function, our observable stop his data stream.

In the next example, our subscriptions only get the first next().

const CNNChannel$ = new Observable((sus) => {
  const loteryNumber = [12, 11, 48, 38];
  sus.next("Number begin in 2 seconds");
  sus.complete();
  setTimeout(() => {
    loteryNumber.map((n) => sus.next(n));
  }, 2000);
});

Feel free to play with the final version in stackbliz

What you can build?

This is my small app build with Rxjs. The app has 3 boxes with a subscribe and unsubscribe button.

The Observable emits different colors. is a color emitter with 3 boxes each of them can subscribe or unsubscribe from them.

https://rjxslearn.netlify.app/

That's it! , that will give you a bit of help with Rxjs. If you enjoyed this post, share it!

Posted on by:

danywalls profile

Dany Paredes

@danywalls

ex .NET guy, my last years building solutions with Vue, Angular, Sass, and Typescript.

Discussion

pic
Editor guide