Rubypic

Ruby Jane Cabagnot

WTH is Reactive Programming?

Reactive programming is a programming paradigm that focuses on how data flows through an application. It is based on the concept of data streams and the propagation of changes.

An Analogy to Understand Reactive Programming

To understand reactive programming, let’s use an analogy of a traffic monitoring system. Imagine you have a network of sensors placed at different intersections in a city. These sensors continuously monitor the traffic flow and report any changes in real-time. Now, instead of manually checking each sensor, you want to build a system that automatically reacts to changes in traffic flow and provides you with relevant information.

In this analogy, the traffic sensors represent data streams, and the system you build represents the reactive programming approach. The sensors continuously emit data (traffic flow information), and your system reacts to these changes by processing and propagating the information to provide meaningful insights.

Now, let’s see a sample code snippet in TypeScript that demonstrates reactive programming using the RxJS library:

import { Observable } from "rxjs";

// Create an observable that emits a sequence of numbers
const numberStream$ = new Observable<number>((subscriber) => {
  let count = 0;
  const intervalId = setInterval(() => {
    subscriber.next(count);
    count++;
  }, 1000);

  // Clean up resources when the observable is unsubscribed
  return () => {
    clearInterval(intervalId);
  };
});

// Subscribe to the number stream and react to changes
const subscription = numberStream$.subscribe((number) => {
  console.log(`Received number: ${number}`);
});

// After 5 seconds, unsubscribe from the stream
setTimeout(() => {
  subscription.unsubscribe();
}, 5000);

In this code, we import the Observable class from the RxJS library, which provides the foundation for reactive programming. We create an observable called numberStream$ that emits a sequence of numbers every second. We then subscribe to this stream and react to changes by logging the received numbers to the console.

The subscribe method takes a callback function that is executed whenever a new value is emitted by the observable. In this case, we log the received number. After 5 seconds, we unsubscribe from the stream using the unsubscribe method to stop receiving further updates.

This example demonstrates the core concepts of reactive programming: creating observables that emit data streams, subscribing to these streams to react to changes, and unsubscribing when we no longer need to receive updates.

I hope this analogy and code example help you understand the concept of reactive programming! Let me know if you have any further questions.