Introduction to Rx

26
Introduction to Rx Reactive Extension to .NET

description

Introduction to Rx. Reactive Extension to .NET. What is Rx?. Observer pattern implementation . Hollywood principle Allows you to provide delegates to be called by another object. Favours Functional over OO. Plenty of extension methods Encourages monadic programming. Multiple targets. - PowerPoint PPT Presentation

Transcript of Introduction to Rx

Introduction to Rx

Introduction to RxReactive Extension to .NET

1What is Rx?Observer pattern implementation Hollywood principleAllows you to provide delegates to be called by another objectIn my opinion, the easiest way to introduce the Reactive Extensions to .NET (here on in called Rx), is to describe it as an implementation of the Observer pattern. It allows you to provide delegates & interfaces to aid in communicating events and asyncrhonous data flows.3Favours Functional over OOPlenty of extension methodsEncourages monadic programmingWhile the Observer pattern is a nice introduction to Rx, Rx is more about functional programming. I think the Observer Pattern was really aimed at OO Languages like Java/C. The Observer pattern helps two classes communicate with each other, however you will see that with Rx queries that they are more interesting from a Functional rather than Object Orientated view point.4Multiple targets.NET 3.5.NET 4.0Silverlight 3Silverlight 4Windows PhoneJavaScript!As the .NET language matures to allow better Functional syntax support it also allows wide support across its various build. The dynamic nature of JavaScript also makes it a prime candidate to target too.

We wont cover any of the JavaScript features in this session.5Linq benefitsComposableTransformativeDeclarativeExtensibleUnitiveIntegratedLinq was built to provide this benefits, it was also aimed to provide these not just for the IEnumerable interface. As rx has proven, you can easily add new interfaces to it and still get Linq support, specifically via extension methods and Query comprehension syntax.6Why Rx?Why would you use Rx and why do you care?Asynchronous DataData being pushedAsync requestsFor any system where you are getting data pushed to you or you are making asynchronous requests, Rx is useful. Examples might be E-Commerce : Changes in Stock or pricing informationInstrumentation : Changes in measurements. Computers or Industrial eg Temperatures, Power consumption, Memory, CPU utilisation.Finance : Price ticks, new Orders on the Book, Charting, CEP, Merging data streams to create new data streams (TWAP/VWAP, margining prices)

8Responsive UIWPF or Silverlight GUIsAJAXComposition of streams of dataConcatenationConcat, OnError/Catch, Retry Merging streamsMerge, Zip, SelectMany, Amb, CombineLatest, ForkJoinGrouping stream dataGroupBy, Window, Buffer, GroupJoin...so what? Observer pattern is old newsObserver pattern is ~15years oldJava has already got the interface.NET has eventsBut...The Java interface is bloated.NET events are pretty silly.Java : http://download.oracle.com/javase/1.4.2/docs/api/java/util/Observable.htmlclass Observable{ void addObserver(Observer o) protected voidclearChanged() int countObservers() void deleteObserver(Observer o) void deleteObservers() boolean hasChanged() void notifyObservers() void notifyObservers(Object arg) protected void setChanged() }.Net events have an odd syntax, dont really handle error scenariosdont have the concept of completingHave poor resource management symantics12Core bits of RxCore bits of RxIObserverIObservableISubjectFactory MethodsExtension MethodsScheduling and ConcurrencyNext we will cover the Core bits of Rx. There is something for everyoneGoF fan boys will love the Pattern mania with Iterator, Observable, Decorator, Disposable, Anonymous Implementation (via Factory) and Dependency Injection.Language geeks will be made content with the familiar Linq syntax and extension method explosion (and that .NET 5 is already being catered for with the AwaitableObservables)Concurrency and Multithreading nerds will get off on the Scheduling and Concurrency featuresTesters will crave the determinism of the TestScheduler14IObservernamespaceSystem{ publicinterfaceIObserver { voidOnNext(Tvalue); voidOnError(Exception error);voidOnCompleted(); }}Can discuss the duality of the IEnumerable interface here.A deep understanding of Iterators will give you a huge boost in understanding Rx.Discuss the Rx grammar and that this is a "formalised" version of the Observer Pattern (Iterator Dual).

15IObservablenamespaceSystem{ publicinterfaceIObservable { IDisposableSubscribe( IObserverobserver); }}Explicitly point out the IDisposable return type that allows for easy resource management.Elude to the fact that there are extension methods for Subscribe that allow you just to pass delegates/actions for the OnNext/Completed/Error.

16SubjectsnamespaceSystem.Collections.Generic{ publicinterfaceISubject : IObserver, IObservable{}

publicinterfaceISubject : ISubject, IObserver, IObservable{ }}17Factory MethodsGenerate / GenerateWithTimeRange / IntervalCreate / CreateWithDisposableEmpty / Return / Never / ThrowFromAsyncPattern / FromEvent

Extension MethodsAggregatesAggregate, Sum, Count, Max, Min, First, Last...FilterWhere, Skip, Take, First, LastGroupingWindow, Buffer, GroupJoinCompositionConcat, Merge, Flow controlAmb, Case, If, While..And include the important one IDisposable Subscribe(Action);19Scheduling and ConcurrencynamespaceSystem.Concurrency{ publicinterfaceIScheduler { DateTimeOffset Now { get; } IDisposableSchedule(Action action); IDisposableSchedule( Action action, TimeSpan dueTime); }}A scheduler implementation effectively allows you to queue or schedule an Action to be performed. Some schedulers will ensure that actions are serialised (ie ones that schedule to the Dispatcher, EventLoop, CurrentThread) and other will not guarantee this (eg NewThread, TaskPool or ThreadPool) .20Scheduler implementationsnamespace System.Concurrency{public static class Scheduler{public static ImmediateScheduler Immediate;public static CurrentThreadScheduler CurrentThread;public static ThreadPoolScheduler ThreadPool;public static NewThreadScheduler NewThread;public static TaskPoolScheduler TaskPool;public static DispatcherScheduler Dispatcher;}}//EventLoopScheduler//TestScheduler//ControlSchedulerDiscuss the difference between the Immediate and CurrentThread implementations. CurrentThread is a trampoline, where Immediate is just actually invoking the Action immediately.21Who would benefit?WPF/Silverlight developersAllowing Rx to schedule work on to the ThreadPool/TaskPoolReturn results on the dispatcherEasily testable (without pushing a Dispatcher frame!) Serverside teams working on streaming data (finance, instrumentation)Compose many feedsEasily testableIQbservable may allow you to send the declaration to the server to process (GPUs/FSharp expressions)

Who would immediately benefit from RX? WPF/Silverlight teams Allowing Rx to schedule work on to the ThreadPool/TaskPool Return results on the dispatcher Easily testable (without pushing a Dispatcher frame!) Serverside teams working on streaming data (finance data, instrumentation data ie Oil and Gas) Compose many feeds to get the final solution. Easily testable IQbservable may allow you to send the declaration to the server to process (GPUs/FSharp expressions) 22Code timeBreak out to show case some code progressions from non-Rx to Rx, to Complex tested Rx 23Best PracticesUse marble diagrams (esp first 12 months)Honour the Completion contractsApply scheduling only at the end consumerAvoid breaking the monad (.First() etc)Avoid Side effects (or be explicit via .Do())Favour composition over creating new operatorsAvoid use of Subjects, favour factories.

Google Rx Design GuidelinesRx design guidelines is a PDF document produced by the Rx team.24Thanks to...Mitch WheatErik Meijers team at MicrosoftLab49

Thanks to Mitch for organising this space in such short notice. Thanks to the team at Microsoft for the great work they are doing and thanks to Lab 49 who pay for this laptop and the kit.25More contentData Developer Center (for the download or get via Nuget)LeeCampbell.blogspot.comEnumerateThis.com (or just talk to James)Rx Forums (which is the same as talking to James)Download the Extensions at http://msdn.microsoft.com/en-us/data/ (just google Reactive Extensions) or via NugetSee the 8/9 part introduction to Rx at LeeCampbell.Blogspot.comJames Miles has some good content at EnumerateThis.com and is also prominent on the Rx Forums which are very active26