Rx allow developers to use the IObservable
interface that represents synchronous data streams to write queries using LINQ. To recap, Rx can be thought of as consisting of three sections:
In this recipe, we will be looking at the LINQ functionality of Rx in more detail.
As observables are just data streams, we can use LINQ to query them. In the following recipe, we will output text to the screen based on a LINQ query.
winformRx
and click on the OK button:winformRx
project and select Manage NuGet Packages… from the context menu:System.Reactive
to search for the NuGet package and click on the Install button:winformRx
project if you expand the References for the project:winformRx
as your startup project by clicking on Set as StartUp Project from the context menu:Observable
keyword. You will notice that the keyword is immediately underlined. This is because you are missing the reference to the LINQ assembly of System.Reactive
:using System.Reactive.Linq
namespace to your project:textBox1
. After you have done that, add a subscription to the variable and tell it to output whatever it finds in the text to the label on the form called label1
:private void Form1_Load(object sender, EventArgs e) { var searchTerm = Observable.FromEventPattern<EventArgs>(textBox1, "TextChanged") .Select(x => ((TextBox)x.Sender).Text); searchTerm.Subscribe(trm => label1.Text = trm); }
Where
condition to the LINQ statement. We will specify that the text
string must only select the text when it ends with a period. This means that the text will only be displayed in the label after each full sentence. As you can see, we aren't doing anything special here. We are merely using standard LINQ to query our data stream and return the results to our searchTerm
variable:private void Form1_Load(object sender, EventArgs e) { var searchTerm = Observable.FromEventPattern<EventArgs>(textBox1, "TextChanged") .Select(x => ((TextBox)x.Sender).Text) .Where(text => text.EndsWith(".")); searchTerm.Subscribe(trm => label1.Text = trm); }
Where
condition:Where
condition is, therefore, working perfectly:The LINQ aspect of Rx allows developers to construct observables. Here are some examples:
Observable.Empty<>
: Returns an empty observable sequenceObservable.Return<>
: Returns an observable sequence containing a single elementObservable.Throw<>
: Returns an observable sequence terminating with an exceptionObservable.Never<>
: Returns a non-terminating observable sequence infinite in durationThe use of LINQ in Rx allows the developer to manipulate and filter the data stream to return exactly what they need.