-10% with HALLOWEEN2021

RxJS: of explained

Publicado por Tomasz Smykowski en

RxJS stands for Reactive Extensions for JavaScript. It is a great library to handle flow of items received by your application. Today you will learn what is one of the most commonly used RxJS operator: of.

The documentation explains it nicely:

But what does it really mean? Let's forget about the documentation for a moment.

The analogy

Imagine your team is fighting against some orks. You decide to throw at them short knives you were wearing on your belt. What happens is that you changed a bunch of knives into a sequence of knives heading towards your opponent. This is how of operator works.

It looks like this:

How to translate this analogy to programming? Why an app should convert a list of objects into a sequence?

The example

Let's say you are writing a dart game. However, in your game, the player has to shoot in the middle of the moving board to win. You wrote a custom RxJS operator called filterWrongClicks that filters a sequence of his clicks. Clicks are sent as x, and y position, where center is hit with { 0, 0 } position. Now, you'd like to test, if it works.

The logic you want to introduce to your app test looks like this:

  1. Send a fake click outside the center of the board
    - check if it was ignored
  2. Send a fake click inside the center of the board
    - check if it was emitted as a hit

The formal way to write it down with RxJS looks like this:

of({ 5, 3 })
   .pipe( filterWrongClicks() )

of({ 0, 0 })
    .pipe( filterWrongClicks() )

First example emits wrong click with position 5,3, and uses your custom operator filterWrongClicks to filter wrong clicks. As a result {5, 3} should not be emitted.

The second example emits proper click with position 0, 0, and uses your custom operator to filter wrong clicks. However since that is a hit, it should be emitted.

There are other operators you can use in the pipe section. However, there are two interesting things about the distinct I want to share with you before this article finishes.


Of operator is a great way to easily create an Observable from a list of arguments. Remember about it, when you want to work on your data with RxJS operators.

Also check out:

Part 1: RxJS throttle
Part 2: RxJS debounce
Part 3: RxJS filter
Part 4: RxJS distinctUntilChanged
Part 5: RxJS takeUntil
Part 6: RxJS map
Part 7: RxJS distinct


0 comentarios

Dejar un comentario

Por favor tenga en cuenta que los comentarios deben ser aprobados antes de ser publicados