Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reactive Extension to .NET

Similar presentations

Presentation on theme: "Reactive Extension to .NET"— Presentation transcript:

1 Reactive Extension to .NET
Introduction to Rx Reactive Extension to .NET

2 What is Rx?

3 Observer pattern implementation
Hollywood principle Allows you to provide delegates to be called by another object In 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.

4 Favours Functional over OO
Plenty of extension methods Encourages monadic programming While 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.

5 Multiple targets .NET 3.5 .NET 4.0 Silverlight 3 Silverlight 4
Windows Phone JavaScript! As the .NET language matures to allow better Functional syntax support it also allows wide support across it’s 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.

6 Linq benefits Composable Transformative Declarative Extensible Unitive
Integrated Linq 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.

7 Why Rx? Why would you use Rx and why do you care?

8 Asynchronous Data Data being pushed Async requests
For 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 information Instrumentation : 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)

9 Responsive UI WPF or Silverlight GUIs AJAX

10 Composition of streams of data
Concatenation Concat, OnError/Catch, Retry Merging streams Merge, Zip, SelectMany, Amb, CombineLatest, ForkJoin Grouping stream data GroupBy, Window, Buffer, GroupJoin

11 what? Observer pattern is old news
Observer pattern is ~15years old Java has already got the interface .NET has events

12 But... The Java interface is bloated .NET events are pretty silly.
class Observable { void addObserver(Observer o) protected void clearChanged() 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 scenarios dont have the concept of completing Have poor resource management symantics

13 Core bits of Rx

14 Core bits of Rx IObserver<T> IObservable<T>
ISubject<T1, T2> Factory Methods Extension Methods Scheduling and Concurrency Next we will cover the Core bits of Rx. There is something for everyone GoF 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 features Testers will crave the determinism of the TestScheduler

15 IObserver<T> namespace System { public interface IObserver<in T> void OnNext(T value); void OnError(Exception error); void OnCompleted(); } Can discuss the duality of the IEnumerable<T> 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).

16 IObservable<T>
namespace System { public interface IObservable<out T> IDisposable Subscribe( IObserver<T> observer); } 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.

17 Subjects namespace System.Collections.Generic { public interface ISubject<in T1, out T2> : IObserver<T1>, IObservable<T2>{ } public interface ISubject<T> : ISubject<T, T>, IObserver<T>, IObservable<T>{ } }

18 Factory Methods Generate / GenerateWithTime Range / Interval
Create / CreateWithDisposable Empty / Return / Never / Throw FromAsyncPattern / FromEvent

19 Extension Methods Aggregates Filter Grouping Composition Flow control
Aggregate, Sum, Count, Max, Min, First, Last... Filter Where, Skip, Take, First, Last Grouping Window, Buffer, GroupJoin Composition Concat, Merge, Flow control Amb, Case, If, While ..And include the important one IDisposable Subscribe(Action<T>);

20 Scheduling and Concurrency
namespace System.Concurrency { public interface IScheduler DateTimeOffset Now { get; } IDisposable Schedule(Action action); IDisposable Schedule( 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) .

21 Scheduler implementations
namespace 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 //ControlScheduler Discuss the difference between the Immediate and CurrentThread implementations. CurrentThread is a trampoline, where Immediate is just actually invoking the Action immediately.

22 Who would benefit? WPF/Silverlight developers
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, instrumentation) Compose many feeds Easily testable IQbservable 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)

23 Code time Break out to show case some code progressions from non-Rx to Rx, to Complex tested Rx

24 Best Practices Use marble diagrams (esp first 12 months)
Honour the Completion contracts Apply scheduling only at the end consumer Avoid breaking the monad (.First() etc) Avoid Side effects (or be explicit via .Do()) Favour composition over creating new operators Avoid use of Subjects, favour factories. Google “Rx Design Guidelines” Rx design guidelines is a PDF document produced by the Rx team.

25 Thanks to... Mitch Wheat Erik Meijer’s team at Microsoft Lab49
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.

26 More content Data Developer Center (for the download or get via Nuget) (or just talk to James) Rx Forums (which is the same as talking to James) Download the Extensions at (just google Reactive Extensions) or via Nuget See the 8/9 part introduction to Rx at James Miles has some good content at and is also prominent on the Rx Forums which are very active

Download ppt "Reactive Extension to .NET"

Similar presentations

Ads by Google