Document directory
- 1.1 What is LINQ
- What is RX? 1.2
I believe you have used language Integrated Query (LINQ). It is a powerful tool that can extract data from a collection. Reactive extensions (RX) is an extension of LINQ. Its goal is to operate asynchronous sets. That is to say, the elements in the set are asynchronously filled, for example, you can obtain data from WebService or cloud and then fill in the set.
LINQ is a language feature introduced since C #3.0, and Rx originated from a study by the Microsoft devlabs team. It extends some of the features of LINQ. Currently, RX supports multiple platforms such as JavaScript and Windows Phone. As data processing becomes more complex, LINQ makes our processing logic simple and clear. Similarly, as more and more data is obtained asynchronously from the cloud, RX makes this asynchronous data processing operation simple and easy to maintain.
This article briefly introduces the importance of LINQ and Rx, and uses code to demonstrate some basic operations of LINQ and Rx.
1. What is LINQ and Rx?
1.1 What is LINQ
LINQ is. net, which is used to query and extract data from objects such as data sets, relational data, and XML files, it provides a unified SQL-like syntax to query data without worrying about different data sources.
LINQ makes our code style more declarative and functional. In my previous article, readers of the query expression and loop control can clearly feel this point. I believe everyone has used Declarative Programming styles, such as attributeclass in C #, XAML in WPF, and F # language, declarative Programming emphasizes the implementation logic and requirements, rather than the specific execution steps. LINQ and Rx are part of C #'s declarative and functional encoding styles. They emphasize how to complete the desired functions, rather than focusing on how to implement them. Compared with the traditional imperative programing style, function programming is simpler and clearer and easier to maintain.
In programming, a program usually consists of several steps. In a specific step, there is usually a loop, and the loop body is the specific logic. In Declarative Programming, a higher abstraction layer is used to express intent. For example, imperative programming is usually like this: "Open all employee sets and traverse the elements in the set to see if the employee is a manager. If yes, the salary is increased by 20%, then, we will update the added salary back to the Collection. "The Declarative Programming style is" increasing the manager's salary by 20%, imperative programming focuses on how to complete a task, while life-style programming focuses on what task to accomplish.
What is RX? 1.2
RX provides a new way to organize and coordinate asynchronous events, such as coordinating multiple asynchronous data streams returned from the cloud. RX can be used to process these data streams in a simple way, greatly simplifying code writing. For example ,. in net, the traditional begin/end asynchronous programming mode can cope with a single asynchronous operation. However, if multiple asynchronous calls at the same time, thread control will make the code more complex. With RX, The begin/end mode becomes a simple method, which makes the code clearer and easier to understand.
The most notable feature of Rx is the use of the observable collection to achieve integrated asynchronous (composing asynchronous) and event-based programming. RX has several features.
- Composing: One of the primary goals of reactive extension is to combine multiple asynchronous operations to make code easier. To achieve this, the data stream must be clearly defined so that the code is very clear and centralized, so that the asynchronous operation code does not flood the entire application.
- Asynchronous: Although RX can not only process asynchronous operations, it greatly simplifies the implementation of asynchronous operations, and the code is easy to understand and thus easy to maintain.
- Event-based: RX simplifies the traditional asynchronous programming method. In the following article, we will see the implementation of the drag-and-drop mode.
- Observable collections: The obervable collection is the core of Rx. It is a collection. The elements of the collection are not filled during the first access. Its importance to the class with RX begins with the importance of the enumerable set to LINQ.
2. Get and install RX
If you use. NET 3 or later versions, LINQ has been integrated into the framework. Similarly, if you have installed the Windows Phone development tool, RX's windowsphone version will be automatically installed. To get the latest RX, visit its official website (http://msdn.microsoft.com/en-us/data/gg577609 ).
3. Differences between RX and LINQ
In terms of processing static set data, LINQ uses SQL-like syntax to operate and use data from different sources. On the contrary, Rx is designed to process the set that will be filled in the future. That is to say, the set type is defined, but the elements in the set may be filled at a certain time in the future.
Before using LINQ, it is required that all elements in the set can be used. That is to say, an initial static set is required for operations using the LINQ set. However, the problem arises. If some data in the collection is still being processed, or the WebService call result in the distance has not been returned, or some real-time data will be constantly added to the collection, so this kind of collection LINQ does not know how to process, because they are not static, the elements in the set will be added at a certain time in the future, and the data arrival events are not sure. Rx is set for this type of data set. It operates such data sets as easily as static data sets operated by LINQ.
It is not easy to understand as you are getting started with LINQ, and there will be similar problems when you get started with Rx. Once you understand and are familiar with the RX syntax, you will feel as friendly as LINQ, and some complicated asynchronous operations can be easily implemented using Rx.
There are many similarities in the technology between LINQ and Rx. After you perform a series of operations on the set in LINQ, such as adding, removing, modifying, and extracting the set, you will get a new set. The new set is only a modified version of the original set. The same is true for Rx. At first glance, collections and data streams seem very different, but they are related in many key areas. This is why we call data streams a collection of the future. Set and data stream are arranged in certain order. LINQ and Rx can perform a series of operations on these sequences and then obtain a new sequence.
Using LINQ and Rx can bring us many benefits. They have the following benefits:
- They are first-class member members in the. NET Framework ). Visual Studio fully supports the intelligent perception and syntax highlighting of LINQ and Rx.
- They can process data produced by various data sources in a unified manner, including databases or XML files.
- They are highly scalable. You can write your own class libraries to extend these frameworks.
- Combination. Both LINQ and Rx can combine a series of complex operations and changes into a small segment of code. Makes the code more concise.
- Declarative style. LINQ and Rx bring some functional programming styles to programming.
- Simplified Implementation. In many cases, one or several pieces of LINQ can be used to easily implement many functions that require complex and obscure statements.
4. Simple examples of RX and LINQ
After talking about this, let's take a simple example to illustrate the usage of LINQ and Rx. You may be familiar with LINQ, so let's take a look at it first.
static void Main(string[] args){ List<Int32> its = Enumerable.Range(1, 15).ToList(); its.Where(i => i % 2 == 0).ToList().ForEach(i => Console.Write("{0} ", i)); Console.ReadKey();}
Output result of the above Code: 2 4 6 8 10 12 14
The above example is very simple. First, use the range method of the enumerable object to initialize a list set, and then use the method expression of LINQ to filter all the even numbers. The code execution of the LINQ statement returns an ienumerable set, then, use the extended method tolist of the ienumerable set to convert it to the list set. When the foreach method is called, an anonymous method is passed in to print all the elements in the set. The entire code is compact and easy to read, and the logic is clear.
The following describes how to use RX to implement the above functions. To use RX, you must add system. reactive. DLL. The default installation path is c: \ Program Files \ microsoft reactive extensions SDK \ v1.0.20.21 \ binaries \. netframework \ v4.0 \ system. reactive. DLL.
static void Main(string[] args){ IObservable<Int32> input = Observable.Range(1, 15); input.Where(i => i % 2 == 0).Subscribe(x => Console.Write("{0} ", x)); Console.ReadKey();}
The code output result is exactly the same as that of the LINQ version, but the internal logic of the program is completely different. In the above Code, the observable object is used to generate an iobservable object set, and then the WHERE clause is used to filter the elements in the set to obtain a new iobservable object. Then, a method is registered for each element of the object, the code above uses an anonymous method to print each element. When an element exists in the Set, the method is called to print the element because the element registers the method.
Different Collection types that can be processed by LINQ and Rx lead to different internal logic. The following describes the enumerable and observable collections.
5. enumerable set and observable set
Both LINQ and Rx are used to operate collections. The set of LINQ Operations implements the ienumerable excuse and can use the foreach statement to traverse the set. The set of RX Operations implements the ienumerable and iqueryable sets, which are called the observable set. You may be familiar with the enumerable set, which is the basis of the foreach statement. I will introduce this in detail in another article, so I will not talk about it here. Next I will mainly look at the observable set.
RX operates on the observable set. The set name is obtained from the observer design mode. The observer mode is based on delegation and events. Therefore, to understand this mode, you need to understand delegation and events, here we recommend the delegation and events in the Article C # of Ziyang. All the elements in the enumebrable set have been filled in the set and are static. You can use the "pull" method to traverse elements from the set for processing. The observable set is different. when creating the set, the elements in the set may be added later. Because the collection registers events, once the elements in the collection arrive, this event is triggered and the information is pushed to the Registrar.
Now in Windows Phone, we will demonstrate how to use these two sets. Add two ListBox controls on the windowphone interface, one filling with the enumerable set and the other using the observable set. The procedure is as follows:
1. Create a Windows Phone project and put two listboxes on the interface, named lblenumerable and lblobservable respectively.
2. Add system. observable. dll and Microsoft. Phone. Reactive. dll, and add a reference to Microsoft. Phone. reactive in the code.
3. Initialize an array variable and fill the two listboxes in two ways respectively.
The complete code is as follows:
Using Microsoft. phone. controls; using Microsoft. phone. reactive; namespace introductionrxphoneapp {public partial class mainpage: phoneapplicationpage {readonly list <string> fruits = new list <string> {"apple", "orange", "banana ", "Pears", "Melon"}; // constructor public mainpage () {initializecomponent (); populatecollection ();} private void populatecollection () {// use the enumerable set to fill fruits. foreach (fruit => lblenumerable. items. add (fruit); // use the observable set to fill the iobservable <string> observable = fruits. toobservable (); observable. subscribe (fruit => lblobservable. items. add (fruit ));}}}
Run the program and you can see that the content in the two drop-down boxes is the same.
6. Conclusion
This article briefly introduces what Rx is and how RX extends the LINQ. The actual code briefly demonstrates the usage of Rx. I hope this article will help you understand RX, because RX and LINQ share many technical aspects, so the next article will introduce some of the core usage of LINQ, so stay tuned!