RxJS Basics in Examples

Artem Diashkin
Aug 27, 2020 · 8 min read

Let's take a look at simple examples of using RxJS, and after that, I hope, you will get the basic idea behind it.

What will be covered in this article:

  • 1. Simplest example
  • 2. Observer
  • 3. Observable
  • 4. Subscription
  • 5. RxJS API List: “index” functions:
  • 5.1 pipe
  • 5.2 concat
  • 5.3 merge
  • 5.4 forkJoin
  • 5.5 fromEvent
  • 5.6 iif
  • 5.7 defer
  • 5.8 partition
  • 5.9 range
  • 5.10 interval
  • 5.11 timer
  • 5.12 bindCallback
  • 5.13 bindNodeCallback
  • 5.14 generate
  • 5.15 onErrorResumeNext
  • 5.16 combineLatest
  • 5.17 isObservable
  • 5.18 pairs
  • 5.19 race
  • 5.20 zip
  • 6. HTTP requests using “ajax”

1. Simplest example

Simple array

As you can see we are just logging to the console each element of the “array”. But how can we do the exact same thing but with the use of the RxJS library?

Example 1 with the use of the “from” function

or like this…

Example 2 with the use of “of” function

The output of those three code examples will be the same:

1
2
three
true

As you can see the main difference between those examples is in the “subscribe” method, so let’s deep dive into that “weird” function and talk about Observers.

2. Observer

First, we should understand what is the Observer, and the answer is very simple — it contains the next, error, and complete functions…

Observer type

… that can be passed as an object…

Using Observer type

… or as properties (we used that approach in example 1 and example 2).

Using Observer as subscribe function properties

Result:

One
Two
Three

And what is subscribe function? It’s like “run” or “execute” command for the Observable (a stream of data), and you are passing an Observer (how to handle that data) to that subscribe function.

The simplest analogy is [].forEach(callback) :

  • array → Observable
  • forEach → subscribe
  • callback → Observer

! Please note that this is an analogy for an easier understanding. You will find out that RxJS is more complex that that example.

Let’s add complete function implementation and take a look at what will be the result:

We will take a look at the error function a little bit later but I think you get the main idea behind it 😉. Error function will be triggered when an Error was thrown in Observable.

3. Observable

For more complex examples we will need to create our own Observable, so let's take a look at how it can be done.

Result:

Hm, wait a minute, where is the error function that should be triggered after 2 seconds? And the answer is — it will NOT be triggered after the “complete” method was invoked.

“If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards. “

— RxJS documentation

Let’s check it out:

Result:

And now we can take a look at a more complex example:

Result:

Now you get the main idea behind Observer and Observable.

4. Subscription

Subscription: represents the execution of an Observable, is primarily useful for canceling the execution.

— RxJS documentation

is primarily useful for canceling the execution? What does it mean? Let’s check it out:

Take a closer look at line 9. And you probably noticed that we are not triggering complete() function…

Because we are canceling further execution we don’t see any “Completed” text in the console result. Keep that in mind 🙂.

5. RxJS API List: “index” functions

RxJS library contains a lot of different index “helper functions” and operators . Here we will cover some of the index list functions:

5.1 pipe

Function that allows you to add RxJS operators to the “flow”

This article is not about the operators (RxJS has more than 100 different operators) but I will show you an example, and you will get the main idea behind them.

Result:

50
60
70
80
✅ Completed!

You can check more about RxJS operators:

buffer bufferCount️ bufferTime️ bufferToggle️ bufferWhen️ concatMap️ concatMapTo️ exhaust️ exhaustMap️ expand

map, mapTo, mergeMap, mergeMapTo, scan, mergeScan, groupBy, pairwise, partition, pluck, switchMap , switchMapTo, window, windowCount, windowTime, windowToggle andwindowWhen

5.2 concat

Concatenates multiple Observables together by sequentially emitting their values, one Observable after the other.

Result:

warning icon

If you would like to emit values from passed Observables concurrently, check out merge instead, especially with optional concurrent parameter.

5.3 merge

Flattens multiple Observables together by blending their values into one Observable.

Result:

By default, all passed Observables will be executed concurrently, but what will happen if we will pass concurrent property equal to 1:

It will act like if we would use concat instead of merge:

5.4 forkJoin

Wait for Observables to complete and then combine the last values they emitted.

Result:

Result:

5.5 fromEvent

Creates an Observable from DOM events, or Node.js EventEmitter events or others.

Result:

5.6 iif

If statement for Observables.

iif accepts a condition function and two Observables. Consumer will subscribe either to the first Observable (if the condition was true) or to the second (if the condition was false).

Result:

If you have more complex logic that requires a decision between more than two Observables, defer will probably be a better choice.

5.7 defer

Creates the Observable lazily, that is, only when it is subscribed.

Result:

1
2
3
4
5

5.8 partition

"Partition” outputs an array with two Observables that partition the values from the source Observable through the given predicate function.

Result:

5.9 range

Emits a sequence of numbers in a range.

Result:

1
2
3
4
5

5.10 interval

Emits incremental numbers periodically in time.

Result:

5.11 timer

Its like “interval”, but you can specify when should the emissions start.

Result:

5.12 bindCallback

Give it a function “f” of type f(x, callback) and it will return a function "g” that when called as g(x) will output an Observable.

Result:

Result 500

And if we will change line 21 to const result$ = bound(-100, 200); , result will be:

Error: "a" < 0

5.13 bindNodeCallback

It’s just like bindCallback, but the callback is expected to be of type callback(error, result).

Result:

🆘 Error: Property "a" is less than zero

5.14 generate

Use it instead of nexting values in a for loop.

Properties of generate function:
initialState: Starting value;
condition: if "true" -> return this value;
iterate: what should be done with the next value;

Result:

1
2
3

5.15 onErrorResumeNext

Execute a series of Observables no matter what, even if it means swallowing errors.

Result:

Please note that “onErrorResumeNext” works like concat → NOT concurrent.

Result:

🟢 One
🟢 One_1

5.16 combineLatest

Whenever any input stream emits a value, it combines the latest values emitted by each input stream

Result:

[ '🟢 One', '🔴 Two' ]
[ '🟢 One_1', '🔴 Two' ]
[ '🟢 One_1', '🔴 Two_1' ]
[ '🟢 One_2', '🔴 Two_1' ]
[ '🟢 One_2', '🔴 Two_2' ]

5.17 isObservable

I think the name of the function speaks for itself 😉

Result:

{ isObservable1: true, isObservable2: true, isObservable3: true }

5.18 pairs

Turn entries of an object into a stream.

Result:

[ 'id', '123' ]
[ 'name', 'John' ]
[ 'email', 'google@gmail.com' ]

5.19 race

Returns an Observable that mirrors the first source Observable to emit an item.

Result:

🔴 One

5.20 zip

Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each of its input Observables.

Result:

[ '🔴 One', '🟡 Two', '🟢 Three' ]

If we will add a map operator — we could modify our result:

Result:

{ 
first: '🔴 One',
second: '🟡 Two',
third: '🟢 Three'
}

Let’s make a few changes to our example:

Result:

6. Http requests using “ajax”

Let’s take a look at how we can make Http requests using “ajax” function from RxJS library.

Please note, that this example will be executed in Node.js, not in a browser, because of that we will need to add some additional code for making this example to work

Result:

LITSLINK

LITSLINK’s team is sharing their experience

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

LITSLINK

LITSLINK

Hands-on up to date experience sharing of the most skilled & talented software developers right here, right now. Subscribe to learn & understand more about the Software World.

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

LITSLINK

LITSLINK

Hands-on up to date experience sharing of the most skilled & talented software developers right here, right now. Subscribe to learn & understand more about the Software World.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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