Reactive Programming
Yeshwanth Chintaginjala
SDE2 @Microsoft|80k+ followers | Ex-PayPal, Ex-Verizon | Data Structures | Algorithms | Problem Solving | System Design(HLD and LLD) | MicroServices(Cloud)
?Definition:
Reactive programming is a programming paradigm that focuses on asynchronous data streams and the propagation of changes. It provides a way to handle and process streams of events or data in a declarative and efficient manner. Reactive programming is often used in systems that require responsiveness, scalability, and real-time data processing.
I find the definitions on the internet confusing let me break it down for you. All around there is a source that keeps asynchronously emitting data as the event of streams, someone processes it as and when the event is generated and does some action
Key principles and components of reactive programming include:
Data Streams: continuous stream of data generated as events
·????????Observables/Publishers: source that generates a stream of events
·????????Subscribers /Observers: these subscribe to event data streams generated by observables and handle them by having separate handlers for each type of event
·????????Operators: Operators provide a way to transform, filter, combine, or manipulate data streams. You can chain them like function operators in js /streams in Java
·????????Backpressure: if there is a fast sender(Observable) and slow receiver(Subscriber), a receiver could ask the sender to slow down, so it makes the processing of data streams nonblocking
·????????Schedulers: Schedulers provide control over the execution context and threading model in reactive programming. They allow you to specify where and how the events emitted by observables are processed, enabling concurrency and parallelism.
Let’s combine all these there is an observable which produces continuous streams of data events, the subscriber subscribes to these events by taking the subscription and handling them using event handlers for each type of event and transforms them applying appropriate operators on them applying backpressure if required and scheduler is executing these based on execution context and threads available.
Examples:
Let’s take an application where we need to give live cricket scores
领英推荐
1.??????You write to a DataBase(DB)/source that emits events continuously and then there is a subscriber in the backend that listens to them applies handlers for example analytics and then updates the UI.
2.??????you need a dashboard that continuously updates with some data change in the DB
A truly reactive application is something where all the layers in the applications are reactive
UI,Backend,DB for example Reactjs <-> SpringReactive/RX dot net <->Cassandra/Postgres
ReactJs Example
Here every time something updates in the UI a component is re rendered, which is reacting to the change in data
import React, { useState } from 'react';
function Counter()
? const [count, setCount] = useState(0);
? const increment = () => {
? ? setCount(count + 1);
? };
? return (
? ? <div>
? ? ? <h1>Count: {count}</h1>
? ? ? <button onClick={increment}>Increment</button>
? ? </div>
? );
}
export default Counter;
{
RX.Net Example
using System
using System.Reactive.Linq;
class Program
{
? ? static void Main()
? ? {
? ? ? ? // Create an observable from an event source (e.g., button clicks)
? ? ? ? IObservable<int> buttonClicks = Observable.FromEventPattern<EventHandler, EventArgs>(
? ? ? ? ? ? handler => Button.Click += handler,
? ? ? ? ? ? handler => Button.Click -= handler)
? ? ? ? ? ? .Select(_ => 1); // Map the event to a value
? ? ? ? // Apply operators to the observable
? ? ? ? IObservable<int> buttonClickCount = buttonClicks
? ? ? ? ? ? .Scan((count, _) => count + 1, 0); // Calculate the running count
? ? ? ? // Subscribe to the observable to consume the events
? ? ? ? IDisposable subscription = buttonClickCount.Subscribe(count => Console.WriteLine($"Button clicked {count} times"));
? ? ? ? Console.WriteLine("Press any key to stop...");
? ? ? ? Console.ReadKey();
? ? ? ? // Dispose the subscription when no longer needed
? ? ? ? subscription.Dispose();
? ? }
}
;
Java Example
import reactor.core.publisher.Flux
public class ReactiveExample {
? ? public static void main(String[] args) {
? ? ? ? // Create a Flux that emits a sequence of integers from 1 to 5
? ? ? ? Flux<Integer> flux = Flux.range(1, 5);
? ? ? ? // Subscribe to the Flux and define reactive processing
? ? ? ? flux.map(i -> i * 2) // Double each emitted value
? ? ? ? ? ? ? ? .filter(i -> i % 3 == 0) // Filter out values that are not divisible by 3
? ? ? ? ? ? ? ? .subscribe(System.out::println); // Print the resulting values
? ? ? ? // Output: 6, 12
? ? }
}
;
"Great insights into reactive programming and its coding paradigm! ?? This post provides a clear understanding of the benefits and principles of reactive programming. It's a valuable read for developers looking to enhance their skills and build more responsive and efficient applications. Thanks for sharing this informative content! For more information visit https://www.dhirubhai.net/feed/update/urn:li:activity:7097922630137094144