.NET Reactive Programming Series of Articles (1): Basic Concepts
introduction
In modern software development, dealing withasynchronous eventsanddata flowIt has become a common requirement, such as user input, network requests, sensor data, etc. These data flows are usuallyUnlimited, asynchronous, real-time, and traditional programming methods often cannot handle these situations gracefully.Reactive ProgrammingIt provides us with a new way of thinking to help developers manage data flows and asynchronous events more naturally and efficiently.
In .NET, the core library for reactive programming is, usually referred to asRx. This article will introduce the basic concepts of reactive programming andThe core components lay the foundation for subsequent in-depth learning.
What is reactive programming?
Reactive Programmingis a kind ofdeclarative programming paradigm, focus onAsynchronous data flowandchange propagation. Simply put, it is a processevent drivenandData changesThe programming method allows the program to automatically respond to external changes.
In reactive programming:
- The data flow can beboundedorunbounded(unlimited).
- Changes in data flow can triggerSubscriberbehavior.
- Subscribers (Observers) can at any timesubscriptionorUnsubscribethese data flows.
Traditional programming vs. reactive programming
traditional programming | Reactive programming |
---|---|
Get data changes by polling | Automatically respond to changes in data flow |
Use callback functions to handle asynchronous | Handling asynchrony via subscription and streaming operators |
Not good at handling unlimited data streams | Focus on handling infinite, asynchronous data streams |
Overview
It was launched by MicrosoftReactive Extensions(Rx)The implementation provides a powerfulObserver patternandOperator library, allowing us to easily manage data flows and asynchronous events.
core components
components | describe |
---|---|
IObservable<T> |
Represents a data flowproducer |
IObserver<T> |
Represents a data flowconsumer(subscriber) |
Subject<T> |
bothproducerTooconsumer |
Operators | Used to convert, filter, combine and other operations on data streams |
Introduction to Observer Pattern
The core is based onObserver Pattern, which is a common design pattern widely used for handling events and callbacks.
The core interface of the observer pattern
-
IObservable
(observable object) - ResponsibleProductiondata flow.
- supply
Subscribe
Method that allows observers to subscribe to its data stream.
-
IObserver
(observer) - ResponsibleConsumptiondata flow.
- The following three methods are defined:
-
OnNext(T value)
: Called when there is new data. -
OnError(Exception error)
: Called when an error occurs in the data flow. -
OnCompleted()
: Called when the data stream ends.
-
Simple sample code
();
// Subscribe to the data stream
(
onNext: value => ($"Received: {value}"),
onError: error => ($"Error: {}"),
onCompleted: () => ("Completed")
);
// publish data
("Hello");
("Reactive Extensions");
();
}
}
Output result:
Received: Hello
Received: Reactive Extensions
Completed
Observable vs. Task
many people willObservableandTaskCompare as they are both used to handle asynchronous operations. But there are some significant differences between the two.
characteristic | Observable | Task |
---|---|---|
data flow | Multiple values/unlimited values | single value |
life cycle | Can be unsubscribed | One-time operation |
time dimension | continuous time series | Single task completed |
Supported operators | Rich conversion, filtering, and combination operators | Few operators |
Brief summary:
- Taskbetter suited to handleSingle asynchronous operation。
- Observablebetter suited to handlecontinuous data floworMultiple asynchronous events。
Three stages of data flow
In reactive programming, there are three stages of data flow:
-
OnNext: Every value in the data stream will pass
OnNext
method passed to subscribers. -
OnError: If an error occurs in the data stream, it will be passed
OnError
Method to notify subscribers. -
OnCompleted: When the data flow ends, it will pass
OnCompleted
Method to notify subscribers.
Hot data flow and cold data flow
exist, data flows can be divided into two types:
1. Cold Observable
- Cold data flow isData will only start to be generated when subscribed。
- Each subscriber will receiveStart from the beginningReceive data.
Example:
var cold = (1, 5);
(x => ($"Subscriber 1: {x}"));
(x => ($"Subscriber 2: {x}"));
Output:
Subscriber 1: 1
Subscriber 1: 2
Subscriber 1: 3
Subscriber 1: 4
Subscriber 1: 5
Subscriber 2: 1
Subscriber 2: 2
Subscriber 2: 3
Subscriber 2: 4
Subscriber 2: 5
2. Hot Observable
- Hot data flow isData is generated at the beginning of the data flow。
- Each subscriber will receiveThe position of the current data streamStart receiving data.
Example:
var hot = new Subject<int>();
(1);
(x => ($"Subscriber: {x}"));
(2);
Output:
Subscriber: 2
Summarize
In this article, we introduced the basic concepts of reactive programming andThe core components of:
- Reactive programming focuses on processingAsynchronous data flow。
-
Provides core interface
IObservable
andIObserver
。 - The life cycle of data flow includes
OnNext
、OnError
andOnCompleted
。 - distinguishedcold data flowandhot data flow。
The next article will introduceBasic operators, including methods to create, transform and filter data streams, stay tuned!