What is RxJS?

Learn via video courses

RxJS, short for Reactive Extension for JavaScript, introduces reactive programming to web development, emphasizing observables for asynchronous tasks, callbacks, and event-driven scenarios. This JavaScript library diverges from traditional imperative programming by enabling applications to respond dynamically to changes, like user interactions or data fetches, rather than relying on explicit code sequences. Analogously, RxJS functions similarly to lodash but specifically targets asynchronous operations. While understanding reactive programming may seem intricate initially, RxJS simplifies handling asynchronous tasks and offers seamless integration with various JavaScript frameworks efficiently.

Prerequisite

You must install rxjs before you can use it in your code. Use the command below:

Or, you may also utilize a CDN:

Brief on Reactive Programming

Reactive programming is a programming paradigm that is concerned with data flows and change. It makes it simple to specify static or dynamic data flows, and the execution model automatically propagates changes across the data flow.

Reactive Extensions code is accessible on practically any computer platform, not just JavaScript, and its objective is to offer Reactive programming capabilities to the computing platform.

The Essential Concepts in RxJS that Solve Async Event Management

Observable

Asynchronous data streams are represented in RxJS through observable sequences, sometimes known as simply observables. Observables might be used to monitor stock quotations or mouse clicks.

Observables are flexible and can be used with push or pull patterns:

Push: We subscribe to the source stream and react to new data as soon as it becomes available when employing the push pattern (emitted). You can listen to a stream and respond appropriately.

Pull: The same operations are used simultaneously when employing the pull pattern. This occurs when arrays, generators, or iterables are used.

Because observables are data streams, you may query them using the observable type's operators. Here are just a few examples of what you can accomplish using observable operators:

  • Filter out stock changes for stocks you don’t own
  • Aggregate—get all the typing in the first five seconds
  • Perform time-based operations on multiple events

Consider the following example:

Output

Observer

Observers are classes that can react to events or things going on around them.

To answer, they must employ the following strategies:

onNext: When an observable emits an item, it calls this method. The item emitted by the observable is sent as a parameter to onNext.

onError: An observable calls this method when it fails to generate the desired data or encounters another problem that causes the observable to halt. The observable will no longer call onNext or onCompleted. The onError method accepts as an argument an indication of what triggered the issue.

onCompleted: If there have been no failures, an observable will call this method after calling onNext for the last time.

Subscription

A subscription is similar to a link between an Observable and an Observer.

An RxJS Subscription is an object that represents a temporary resource, often the execution of an Observable. When we build an observable, we must subscribe to it in order for it to be executed.

A Subscription has one key function, unsubscribe(), that accepts no arguments and is used only to dispose of/release resources or cancel Observable executions of the subscription's resource.

Operators

Operators are responsible for a wide range of responsibilities. Their goal is to make it easier to observe an observable. Operators do the following tasks:

  • Create observables
  • Combine observables
  • Filter observables
  • Handle errors
  • Perform utilities

The majority of operators act on one observable and return another observable. This allows you to apply operators in a chain one after the other. Each operator in the chain affects the observable produced by the preceding operator's operation.

Subject

You may subscribe to a Subject by giving an Observer, which will begin receiving values normally. The Observer cannot distinguish whether the Observable execution is coming from a simple unicast Observable or a Subject.

The Subject varies from the Observable in that it can influence the stream's content after it has been created.

A Subject is a subclass of the RxJS library's Observable that allows us to multicast values to components that have subscribed to it. When Subject emits a value, every one of its subscribers receives a notification.

It has three methods:

next(value)- Use to emit a new value. error(error) - Use to send error notifications. complete()- This method implies that the Subject has finished its task. Once the complete() method is invoked, calling next() or error() won’t have any effect.

Schedulers

Schedulers are entities that determine when a subscription begins and when notifications are sent. It consists of three parts:

data structure: It understands how to store and queue jobs according to priority or other factors.

execution context: The execution context specifies where and when tasks are carried out. It can be done immediately or later.

virtual clock: Tasks are run in relation to the time indicated by the scheduler's now() getter function.

Subject is Hot Observable

Subjects, as opposed to normal Observables, are "Hot." A hot Observable is one that can begin emitting events before you subscribe to it. This indicates you may have missed past occurrences that have already occurred.

There are two types of Observables: HOT and COLD.

Cold Observable

Cold observable is an Observable that does not emit items until a subscriber subscribes. Also, If we have more than one subscriber, the observable will emit a series of items to each subscriber one by one.

Hot Observable

Hot observable are those that do not require a subscription. When they are created, they begin to spew stuff. They do not re-emit the item sequence for a new subscriber. In contrast to cold observable, when an item is emitted by a hot observable, all subscribers who have subscribed will receive the emitted item all at once.

Every Subject is an Observer

You may subscribe to a Subject by giving an Observer, which will begin receiving values normally. The Observer cannot distinguish whether the Observable execution is coming from a simple unicast Observable or a Subject.

Subjects are Multicast

Subjects are Multicast because subscribe does not initiate a new execution that provides values within the Subject. It just registers the supplied Observer in a list of Observers, much like addListener does in other libraries and languages.

A Subject has the ability to multicast. This behavior does not need any particular effort on your part.

Here's a quick multicast demonstration:

Multicast vs Unicast

UnicastMulticast
It has a single sender and a single receiver.It consists of one or more senders as well as several recipients.

Subjects Maintain a List of Subscribers

When a subscriber subscribes to a subject, the subject keeps a list of subscribers and emits the values to all subscribers when it is emitted.

Other Types of Subjects

There are several types of subjects, such as BehaviorSubject, ReplaySubject, and AsyncSubject.

Behavior Subject

The BehaviorSubject has the property of storing the "current" value. This implies you can always receive the most recently emitted value from the BehaviorSubject.

ReplaySubject

In that it may deliver "old" data to new subscribers, the ReplaySubject is similar to the BehaviorSubject. It does, however, have the additional capability of recording a portion of the observable execution and so storing multiple old values, and "replaying" them to new subscribers.

AsyncSubject

While both the BehaviorSubject and the ReplaySubject store values, the AsyncSubject functions in a somewhat different way. The AsyncSubject is a Subject variation that only sends the last value of the Observable execution to its subscribers after the execution is finished.

Purity

RxJS's ability to construct values using pure functions is what makes it so powerful. That implies your code is less likely to contain mistakes.

You isolate the state using RxJS:

The scan operator works just like reduce for arrays. It accepts a value that is sent to a callback. The callback's returned value will then become the next value exposed the next time the callback runs.

Flow

RxJS offers a wide range of operators that allow you to manage how events flow through your observables.

This is how you would allow at most one click per second:

filter, delay, debounceTime, take, takeUntil, distinct, distinctUntilChanged, and other flow control operators are available.

Values

You can change the values that are transmitted through your observables.

Here's how to include the current mouse x location with each click:

Other value-creating operations include pluck, pairwise, sample, and so on.

Conclusion

  • RxJS is a javascript library that brings the concept of reactive programming
  • Some fundamental concepts:
    • Observable
    • Observer
    • Subscription
    • Operators
    • Subject
    • Schedulers
  • Subjects are Multicast
  • Different types of subjects are available
    • BehaviorSubject
    • ReplaySubject
    • AsyncSubject
  • Different operators are available to perform operations