Reactive Extensions for .NetScott WeinsteinPrincipalLab49weblogs.asp.net/sweinstein   / @ScottWeinstein
What is it?The Reactive Extensions for .Net are a new API from MS Dev labs to enable “Linq over Events”Why should I care?Offers a better programming model then Events
Some Concepts
Please sir, can I have some more?
Bid 20, bid 20.2, bid 20.8,…
PullFor pull, data is processed at the leisure of the consumer. The consumer “pulls” the next item from the producerCommon examples include:reading from a filesumming the numbers in an arrayiterating though a database querytraversing a directory listingpaging through an Amazon search
Push	For push, data is send via demands of the source. The producer pushes the data to the consumer.Common examples include:Device measurements such astimelight heatUser triggered data such as Mouse & Keyboard eventsUI eventsSales transactionsAsynchronous code
Push & PullIn both scenarios, data moves from the producer to the consumer
Push & Pull in .NetIn .Net Pulled data is exposed via common interface pairIEnumerable/IEnumeratorThere is no other wayForeach and Linq are build on these interfacesPushed data is exposed viaEventsAd-hoc delegate callbacksAd-hoc subscribe/callback interfacesBeginXXX/EndXXX Async pattern3rd party attempts at Linq for Pushed data (Clinq,Slinq,PushLinq)Each implementation is unique is its own special way
LINQLINQprovides a composable and standard way to do list manipulationsThe Reactive Extensions (RX) attempt toProvide a common interface for Pushed dataIObservable/IObserverEnable Linq over Pushed data, providing composiblity and standard operators
DemoSimple Temperature Alerts
Events to Observables Demo
Func and Action and LambdasFunc<int> a;Func<int,int,int> add = (a,b) => a+b;Action<T> t;Action <T,T> tt;
Some (Category) TheoryThere is a formal basis for the RXDuality, as such, is the assertion that truth is invariant under this operation on statements. In other words, if a statement is true about C, then its dual statement is true about Cop. Also, if a statement is false about C, then its dual has to be false about Cop.Informally, these conditions state that the dual of a statement is formed by reversing arrows and compositions.What this means is that if we can create a Dual of IEnumerable then all of Linq will work over pushed data
Dualizing IEnumeratorinterface IEnumerator<T> {    T Current { get; } // but can throw an exception    bool MoveNext();    void Reset(); // not used}Reverse the arrowsinterface IObserverDraft1<T> {    SetCurrent(T value); // but need to handle an exception    MoveNext(bool can) ;}
Dualizing IEnumerator (2/2)interface IObserverDraft2<T>{    OnNext(T value);     OnError(Exception ex);    MoveNext(bool can) ; //but called every time!}interface IObserver<T> {    OnNext(T value);     OnError(Exception ex);    OnCompleted(); // only called once}
Dualizing IEnumerableinterface IEnumerable<T> {    IEnumerator<T> GetEnumerator();}Reverse the arrowspublic interface IObservableDraft1<T> {// But how do I stop observing?    SetObserver(IObserver<T> obs); }
Dualizing IEnumerable (2/2)interface IObservableDraft2<T> {    Subscribe(IObserver<T> obs);// can I be more composable?    Unsubscribe(IObserver<T> obs); }interface IObservable<T> {    IDisposable Subscribe(IObserver<T> obs);}
Terse functional explanationEnumerable:() –> (() –> Option<T>)FuncEnumerable<T> –> 		Func<Func<Option<T>>>Observable(Option<T> –> ()) –> ()FuncObservable<T> –> 			Action<Action<Option<T>>>
CombinatorsDemo Implement Where()
Some useful CombinatorsCombineLatestDoForkJoinGroupByScanHoldUntilChangedIntervalMergeObserveOnDispatcherSampleThrottleSelectSelectManyWhereZip
How to create Observables?CreateCreateWithDisposableFromAsyncPatternFromEventGenerateISubjectIn general, it’s a mistake to create custom implementations of IObservable or IObserverWhen might it be ok to break this rule?
Streaming OLAP DemoScan, GroupBy, Where, Zip, Merge, SelectMany
MergeIObservable<T> aIObservable<T> bA.Merge(B) == IObservable<T> ==
ZipIObservable<T> aIObservable<Y> ba.Zip(b, selector) == IObservable<Z> ==
GroupingIObservable<T>IGroupedObservable<TKey, TElement>KeyIObservable<IGroupedObservable<Tkey,TElement>>KeyAKeyBKeyC
Hot & ColdObservables (and Enumerables) come in two flavorsHotValues exist outside of subscriptionColdValue only exist because of subscriptionCold observables can be prone to side-effectsToArray() is one method for making cold Enumerables hot, Replay() and Publish for Observables (and now Enumerables)
Hot and Cold Demo
Code vs. DataRX has an alternate method of representing stream eventsInterface defines a code-centric viewOnNextOnErrorOnCompletedNotification defines a data-centric viewnew Notification<T>.OnNext(T next)Where is this useful?
SchedulersRX introduces Schedulers for explicit control Which thread do subscriptions run onHow is time representedControlSchedulerCurrentThreadSchedulerDispatcherSchedulerImmediateSchedulerNewThreadSchedulerSynchronizationContextSchedulerTaskPoolSchedulerThreadPoolScheduler
Topics not coveredJoinsSubjects combine Observability and Enumerablility into a single class. BehaviorSubject<T>AsyncSubject<T>ReplaySubject<T>Subject<T>
How to get it?Download from the DevLabs: Reactive Extensions for .NET (Rx) site.Net 4In .Net 4 – IObservable/IObserver are part of the BCL.Net 3.5 SP1Silverlight 3JavascriptCurrent license is “go-live” however the API is still evolving
ResourcesReactive Extensions for .NetForumsVideoshttp://weblogs.asp.net/sweinstein
Delayed Expensive Search
DemoAsync webpage download

Intro to RX

  • 1.
    Reactive Extensions for.NetScott WeinsteinPrincipalLab49weblogs.asp.net/sweinstein / @ScottWeinstein
  • 2.
    What is it?TheReactive Extensions for .Net are a new API from MS Dev labs to enable “Linq over Events”Why should I care?Offers a better programming model then Events
  • 3.
  • 4.
    Please sir, canI have some more?
  • 5.
    Bid 20, bid20.2, bid 20.8,…
  • 6.
    PullFor pull, datais processed at the leisure of the consumer. The consumer “pulls” the next item from the producerCommon examples include:reading from a filesumming the numbers in an arrayiterating though a database querytraversing a directory listingpaging through an Amazon search
  • 7.
    Push For push, datais send via demands of the source. The producer pushes the data to the consumer.Common examples include:Device measurements such astimelight heatUser triggered data such as Mouse & Keyboard eventsUI eventsSales transactionsAsynchronous code
  • 8.
    Push & PullInboth scenarios, data moves from the producer to the consumer
  • 9.
    Push & Pullin .NetIn .Net Pulled data is exposed via common interface pairIEnumerable/IEnumeratorThere is no other wayForeach and Linq are build on these interfacesPushed data is exposed viaEventsAd-hoc delegate callbacksAd-hoc subscribe/callback interfacesBeginXXX/EndXXX Async pattern3rd party attempts at Linq for Pushed data (Clinq,Slinq,PushLinq)Each implementation is unique is its own special way
  • 10.
    LINQLINQprovides a composableand standard way to do list manipulationsThe Reactive Extensions (RX) attempt toProvide a common interface for Pushed dataIObservable/IObserverEnable Linq over Pushed data, providing composiblity and standard operators
  • 11.
  • 12.
  • 13.
    Func and Actionand LambdasFunc<int> a;Func<int,int,int> add = (a,b) => a+b;Action<T> t;Action <T,T> tt;
  • 14.
    Some (Category) TheoryThereis a formal basis for the RXDuality, as such, is the assertion that truth is invariant under this operation on statements. In other words, if a statement is true about C, then its dual statement is true about Cop. Also, if a statement is false about C, then its dual has to be false about Cop.Informally, these conditions state that the dual of a statement is formed by reversing arrows and compositions.What this means is that if we can create a Dual of IEnumerable then all of Linq will work over pushed data
  • 15.
    Dualizing IEnumeratorinterface IEnumerator<T>{ T Current { get; } // but can throw an exception bool MoveNext(); void Reset(); // not used}Reverse the arrowsinterface IObserverDraft1<T> { SetCurrent(T value); // but need to handle an exception MoveNext(bool can) ;}
  • 16.
    Dualizing IEnumerator (2/2)interfaceIObserverDraft2<T>{ OnNext(T value); OnError(Exception ex); MoveNext(bool can) ; //but called every time!}interface IObserver<T> { OnNext(T value); OnError(Exception ex); OnCompleted(); // only called once}
  • 17.
    Dualizing IEnumerableinterface IEnumerable<T>{ IEnumerator<T> GetEnumerator();}Reverse the arrowspublic interface IObservableDraft1<T> {// But how do I stop observing? SetObserver(IObserver<T> obs); }
  • 18.
    Dualizing IEnumerable (2/2)interfaceIObservableDraft2<T> { Subscribe(IObserver<T> obs);// can I be more composable? Unsubscribe(IObserver<T> obs); }interface IObservable<T> { IDisposable Subscribe(IObserver<T> obs);}
  • 19.
    Terse functional explanationEnumerable:()–> (() –> Option<T>)FuncEnumerable<T> –> Func<Func<Option<T>>>Observable(Option<T> –> ()) –> ()FuncObservable<T> –> Action<Action<Option<T>>>
  • 20.
  • 21.
  • 22.
    How to createObservables?CreateCreateWithDisposableFromAsyncPatternFromEventGenerateISubjectIn general, it’s a mistake to create custom implementations of IObservable or IObserverWhen might it be ok to break this rule?
  • 23.
    Streaming OLAP DemoScan,GroupBy, Where, Zip, Merge, SelectMany
  • 24.
  • 25.
    ZipIObservable<T> aIObservable<Y> ba.Zip(b,selector) == IObservable<Z> ==
  • 26.
  • 27.
    Hot & ColdObservables(and Enumerables) come in two flavorsHotValues exist outside of subscriptionColdValue only exist because of subscriptionCold observables can be prone to side-effectsToArray() is one method for making cold Enumerables hot, Replay() and Publish for Observables (and now Enumerables)
  • 28.
  • 29.
    Code vs. DataRXhas an alternate method of representing stream eventsInterface defines a code-centric viewOnNextOnErrorOnCompletedNotification defines a data-centric viewnew Notification<T>.OnNext(T next)Where is this useful?
  • 30.
    SchedulersRX introduces Schedulersfor explicit control Which thread do subscriptions run onHow is time representedControlSchedulerCurrentThreadSchedulerDispatcherSchedulerImmediateSchedulerNewThreadSchedulerSynchronizationContextSchedulerTaskPoolSchedulerThreadPoolScheduler
  • 31.
    Topics not coveredJoinsSubjectscombine Observability and Enumerablility into a single class. BehaviorSubject<T>AsyncSubject<T>ReplaySubject<T>Subject<T>
  • 32.
    How to getit?Download from the DevLabs: Reactive Extensions for .NET (Rx) site.Net 4In .Net 4 – IObservable/IObserver are part of the BCL.Net 3.5 SP1Silverlight 3JavascriptCurrent license is “go-live” however the API is still evolving
  • 33.
    ResourcesReactive Extensions for.NetForumsVideoshttp://weblogs.asp.net/sweinstein
  • 34.
  • 35.