What Is Rxjs And Why You Should Be Using It?
If you have been using Lodash, then you will probably have an understanding of what the following statement means:
Think of RxJS as Lodash for events.
When you think of RxJs, think of Asynchronous(async) way of writing code. Basically RxJs is a library for managing Async events in a funnel flow method. Let’s take an example of how to control how many times a button is clicked:
Vanilla javaScript Way
1 2 3 4 5 6 7 8 9 |
|
RxJs Observable Way
1 2 3 4 5 6 |
|
RxJs provides one core type, the observable
, satellite types (Observer, Schedulers, Subjects)
and operators (map, filter, reduce, every, etc)
to allow handling asynchronous events as collections. Let’s take a look at 2 concepts of RxJs:
RxJs Flow
In our first example, where we controlled the number of time a button can be click, that is known as a flow
. RxJs uses Operators
to control how events flow.
1 2 3 4 |
|
RxJs has other very useful flow control operators to manage how events flow. Example of such operators are filter, delay, debounceTime, take, takeUntil, distinct, distinctUntilChanged
RxJs Values
How to return values from an Rxjs ?
RxJs has a number value producing operators such as subscribe
operator.
Subscribe
The Subscribe operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable, or to receive error or completed notifications from the Observable, it must first subscribe to that Observable with this operator. Let’s take a look at an example comparison on returning values between Vanilla JavaScript and RxJs. Here's how you can add the current mouse x position for every click, in plain JavaScript:
Vanilla javaScript Way
1 2 3 4 5 6 7 8 |
|
RxJs Way
1 2 3 4 5 6 |
|
Other value producing operators are pluck, pairwise, sample