Reactive Programming in JavaScript with RxJS

The Reactive Manifesto

Reactive Systems are:

Responsive:

 

The system responds in a timely manner if at all possible. Responsiveness is the cornerstone of usability and utility, but more than that, responsiveness means that problems may be detected quickly and dealt with effectively. Responsive systems focus on providing rapid and consistent response times, establishing reliable upper bounds so they deliver a consistent quality of service. This consistent behavior in turn simplifies error handling, builds end user confidence, and encourages further interaction.

Resilient:

 

The system stays responsive in the face of failure. This applies not only to highly-available, mission-critical systems — any system that is not resilient will be unresponsive after a failure. Resilience is achieved by replication, containment, isolation and delegation. Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.

Elastic:

 

The system stays responsive under varying workload. Reactive Systems can react to changes in the input rate by increasing or decreasing the resources allocated to service these inputs. This implies designs that have no contention points or central bottlenecks, resulting in the ability to shard or replicate components and distribute inputs among them. Reactive Systems support predictive, as well as Reactive, scaling algorithms by providing relevant live performance measures. They achieve elasticity in a cost-effective way on commodity hardware and software platforms.

Message Driven:

 

Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation and location transparency. This boundary also provides the means to delegate failures as messages. Employing explicit message-passing enables load management, elasticity, and flow control by shaping and monitoring the message queues in the system and applying back-pressure when necessary. Location transparent messaging as a means of communication makes it possible for the management of failure to work with the same constructs and semantics across a cluster or within a single host. Non-blocking communication allows recipients to only consume resources while active, leading to less system overhead.

Interactive Vs. Reactive (pull Vs. Push)

Interactive: going each day to the nearby store (or several stores in case that the nearby store does not have all of your favorite journals), collect the journals, wait on the payment queue, pay for it and return home for reading.

Reactive: subscribe to journal delivery service which will send the journals to your door front each day.

Pull collections are what we are all used to in programming. The most striking example is the array.

 

const arr = [1,2,3,4,5];


It already has data, it will not change this data, but it can give it on request.

 

arr.forEach(console.log);

 

Also, before you do something with the data, you can somehow handle them.

 

              arr.map(i => i+1)
                 .map(I => “my number is ”+i)
                 .forEach(console.log);

And now let's imagine that initially there is no data in the collection, but it will definitely inform you that they have appeared (Push). And at the same time, we still can apply the necessary transformations to this collection.


For example:

 

       source.map(i => i+1)
             .map(I => “my number is ”+i)
             .forEach(console.log);

 

 

When a value appears in the source, for example, 1, console.log will display “my number is 1”.

RxJS is JavaScript library for transforming, composing and querying asynchronous streams of data. RxJS can be used both in the browser or in the server-side using Node.js.

The hardest part of the learning RxJS is “Thinking in Reactively".

Think of RxJS as “LoDash” for handling asynchronous events.

So, What Exactly, Reactive Programming is?

Reactive programming is a programming paradigm for writing code, mainly concerned with asynchronous data streams.

Stream

A stream is a sequence of ongoing events ordered in time.

Types of async operations in modern web applications

  • DOM Events- (mouse events, touch events, keyboard events, form events etc)
  • Animations - (CSS Transitions and Animations, requestAnimationFrame etc)
  • AJAX
  • WebSockets
  • SSE - Server-Sent Events
  • Alternative inputs (voice, joystick etc)

Observable

  • An Observable is just a function, with a few special characteristics. It takes in an “observer” (an object with “next”, “error” and “complete” methods on it), and returns cancellation logic.
  • Observables provide support for passing messages between publishers and subscribers in your application.
  • Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values.
  • Observables are lazy. It doesn't start producing data untill you subscribe to it.
  • subscribe() returns a subscription, on which a consumer can be call unsubscribe() to cancel the subscription and tear donw the producer.
  • RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on. 

Observer

  • An observer is object literal with next(), error() and complete()functions. In the above example, the observer is the object literal we pass into our .subscribe() method.
  • When an Observable produces values, it then informs the observer, by calling .next() method when a new value was successfully captured and .error() when an error occurred.
  • When we subscribe to an Observable, it will keep passing values to an observer until the complete signal.

Subscription

  • An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.
  • A Subscription has one important method, unsubscribe(), that takes no argument and just disposes of the resource held by the subscription.

Subject

  • RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.
  • A subject in RxJS is a special hybrid that can act as both an Observable and an Observer at the same time.

Operators

  • Operators are functions that build on the Observables foundation to enable sophisticated manipulation of collections.
  • An Operator is essentially a pure function which takes one Observable as input and generates another Observable as output.
  • There are operators for different purposes, and they may be categorized as creation, transformation, filtering, combination, multicasting, error handling, utility etc.
  • Operators pass each value from one operator to the next before proceeding to the next value in the set. This is different from array operators (map and filter) which will process the entire array at each step.
  • RxJS provides many operators, but only a handful are used frequently. For a list of operators and usage samples, visit the RxJS API Documentation.
Made with Slides.com