What is LINQ to events a.k.a RX Framework?

前端 未结 4 1739
自闭症患者
自闭症患者 2020-12-23 09:49

What is LINQ to events a.k.a RX Framework aka the Reactive Extensions in .NET 4.0 (but also available as backported versions)?

In other words, what

4条回答
  •  独厮守ぢ
    2020-12-23 10:39

    .NET Rx team (this is not an official name) found that any push sequence (events, callbacks) can be viewed as a pull sequence (as we normally do while accessing enumerables) as well – or they are Dual in nature. In short observer/observable pattern is the dual of enumeration pattern.

    So what is cool about about this duality?

    Anything you do with Pull sequences (read declarative style coding) is applicable to push sequences as well. Here are few aspects. You can create Observables from existing events and then use them as first class citizens in .NET – i.e, you may create an observable from an event, and expose the same as a property.

    As IObservable is the mathematical dual of IEnumerable, .NET Rx facilitates LINQ over push sequences like Events, much like LINQ over IEnumerables

    It gives greater freedom to compose new events – you can create specific events out of general events.

    .NET Rx introduces two interfaces, IObservable and IObserver that "provides an alternative to using input and output adapters as the producer and consumer of event sources and sinks" and this will soon become the de-facto for writing asynchronous code in a declarative manner. Here is a quick example.

    //Create an observable for MouseLeftButtonDown
    
    var mouseLeftDown=Observable.FromEvent  
            (mycontrol,"MouseLeftButtonDown");  
    
    //Query the above observable just to select the points
    var points = from ev in mouseEvents  
                     select ev.EventArgs.GetPosition(this);  
    
    //Show points in the window's title, when ever user
    //presses the left button of the mouse
    points.Subscribe(p => this.Title = "Location ="  
                                            + p.X + "," + p.Y);
    

    You may go through these posts as well to get the head and tail in detail. Also have a look at the relates source code as well.

    • Part I - System.Reactive or the .NET Reactive Extensions (Rx) – Concepts and First Look
    • Part II - LINQ To Events - More on .NET Reactive Extensions (Rx)
    • Part III - LINQ To Events - Generating GetEventName() Wrapper Methods using T4 Text Templates

    Check out this set of articles

提交回复
热议问题