35
Reactive Extensions for .Net Scott Weinstein Principal Lab49 weblogs.asp.net/ sweinstein / @ScottWeinstein

Intro to RX

Embed Size (px)

DESCRIPTION

Introduction to Reactive Extensions for .Net

Citation preview

Page 1: Intro to RX

Reactive Extensions for .Net

Scott WeinsteinPrincipal

Lab49weblogs.asp.net/sweinstein / @ScottWeinstein

Page 2: Intro to RX

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

Page 3: Intro to RX

Some Concepts

Page 4: Intro to RX

Please sir, can I have some more?

Page 5: Intro to RX

Bid 20, bid 20.2, bid 20.8,…

Page 6: Intro to RX

Pull•For pull, data is processed at the leisure

of the consumer. •The consumer “pulls” the next item from

the producer•Common examples include:

reading from a file summing the numbers in an array iterating though a database query traversing a directory listing paging through an Amazon search

Page 7: Intro to RX

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 as time light heat

▫ User triggered data such as Mouse & Keyboard events UI events Sales transactions

▫ Asynchronous code

Page 8: Intro to RX

Push & Pull•In both scenarios, data moves from the

producer to the consumer

Page 9: Intro to RX

Push & Pull in .Net• In .Net Pulled data is exposed via common interface

pair▫ IEnumerable/IEnumerator▫ There is no other way

Foreach and Linq are build on these interfaces• Pushed data is exposed via

▫ Events▫ Ad-hoc delegate callbacks▫ Ad-hoc subscribe/callback interfaces▫ BeginXXX/EndXXX Async pattern▫ 3rd party attempts at Linq for Pushed data

(Clinq,Slinq,PushLinq)• Each implementation is unique is its own special way

Page 10: Intro to RX

LINQ•LINQ provides a composable and

standard way to do list manipulations

•The Reactive Extensions (RX) attempt to▫Provide a common interface for Pushed

data IObservable/IObserver

▫Enable Linq over Pushed data, providing composiblity and standard operators

Page 11: Intro to RX

DemoSimple Temperature Alerts

Page 12: Intro to RX

Events to Observables Demo

Page 13: Intro to RX

Func and Action and Lambdas•Func<int> a;

•Func<int,int,int> add = (a,b) => a+b;

•Action<T> t;•Action <T,T> tt;

Page 14: Intro to RX

Some (Category) Theory•There is a formal basis for the RX

Duality, 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

Page 15: Intro to RX

Dualizing IEnumeratorinterface IEnumerator<T> { T Current { get; } // but can throw an exception bool MoveNext(); void Reset(); // not used}

• Reverse the arrows

interface IObserverDraft1<T> { SetCurrent(T value); // but need to handle an exception MoveNext(bool can) ;}

Page 16: Intro to RX

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}

Page 17: Intro to RX

Dualizing IEnumerableinterface IEnumerable<T> { IEnumerator<T> GetEnumerator();}

•Reverse the arrowspublic interface IObservableDraft1<T> {

// But how do I stop observing?

SetObserver(IObserver<T> obs); }

Page 18: Intro to RX

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);}

Page 19: Intro to RX

Terse functional explanation•Enumerable:

▫() –> (() –> Option<T>)▫FuncEnumerable<T> –> Func<Func<Option<T>>>

•Observable▫(Option<T> –> ()) –> ()▫FuncObservable<T> –> Action<Action<Option<T>>>

Page 20: Intro to RX

Combinators• Demo

▫ Implement Where()

Page 21: Intro to RX

Some useful Combinators▫ CombineLatest▫ Do▫ ForkJoin▫ GroupBy▫ Scan▫ HoldUntilChanged

▫ Interval▫ Merge▫ ObserveOnDispatcher▫ Sample▫ Throttle▫ Select▫ SelectMany▫ Where▫ Zip

Page 22: Intro to RX

How to create Observables?▫Create▫CreateWithDisposable▫FromAsyncPattern▫FromEvent▫Generate▫ISubject

▫In general, it’s a mistake to create custom implementations of IObservable or IObserver When might it be ok to break this rule?

Page 23: Intro to RX

Streaming OLAP DemoScan, GroupBy, Where, Zip, Merge, SelectMany

Page 24: Intro to RX

Merge•IObservable<T> a

•IObservable<T> b

•A.Merge(B) == IObservable<T> ==

Page 25: Intro to RX

Zip•IObservable<T> a

•IObservable<Y> b

•a.Zip(b, selector) == IObservable<Z> ==

Page 26: Intro to RX

GroupingT3 T2 T1

IObservable<T>

T3 T2 T1

IGroupedObservable<TKey, TElement>

Key

IObservable<IGroupedObservable<Tkey,TElement>>

T3 T2 T1KeyA

T3 T2 T1KeyB

T3 T2 T1KeyC

Page 27: Intro to RX

Hot & Cold• Observables (and Enumerables) come in two

flavors• Hot

▫ Values exist outside of subscription• Cold

▫ Value only exist because of subscription

• Cold observables can be prone to side-effects• ToArray() is one method for making cold

Enumerables hot, Replay() and Publish for Observables (and now Enumerables)

Page 28: Intro to RX

Hot and Cold Demo

Page 29: Intro to RX

Code vs. Data•RX has an alternate method of

representing stream events•Interface defines a code-centric view

▫OnNext▫OnError▫OnCompleted

•Notification defines a data-centric view▫new Notification<T>.OnNext(T next)

•Where is this useful?

Page 30: Intro to RX

Schedulers•RX introduces Schedulers for explicit

control▫ Which thread do subscriptions run on▫How is time represented

▫ ControlScheduler CurrentThreadScheduler▫ DispatcherScheduler ImmediateScheduler▫ NewThreadScheduler SynchronizationContextScheduler▫ TaskPoolScheduler ThreadPoolScheduler

Page 31: Intro to RX

Topics not covered•Joins•Subjects

▫combine Observability and Enumerablility into a single class.

▫BehaviorSubject<T>▫AsyncSubject<T>▫ReplaySubject<T>▫Subject<T>

Page 32: Intro to RX

How to get it?•Download from the DevLabs: Reactive

Extensions for .NET (Rx) site▫.Net 4

In .Net 4 – IObservable/IObserver are part of the BCL

▫.Net 3.5 SP1▫Silverlight 3▫Javascript

•Current license is “go-live” however the API is still evolving

Page 34: Intro to RX

Delayed Expensive Search

Page 35: Intro to RX

DemoAsync webpage download