An introduction to the Reactive Extensions for NET









































- Slides: 41
An introduction to the Reactive Extensions for. NET and Java. Script Chris Alcock Developer South West 2010
About Me • First time Conference Speaker • Based in Liverpool, UK • Software Developer using. NET stack @ New Mind • 2010 ASP. NET MVP • The Morning Brew - Daily. NET Software, News and Views and Community round up http: //The. Morning. Brew. Net Email: calcock@incanus. co. uk Twitter: @calcock Personal Blog: http: //cwa. me. uk 2
Agenda • What is Reactive / Interactive? • How do we get to Reactive? • Reactive Extensions in C# • Events • IEnumerable • LINQ • Asynchronous Operations • Reactive Extensions for Java. Script, j. Query Integration 3
Getting the bits… Available from Microsoft Dev. Labs http: //tinyurl. com/Reactive. Extensions • Under Active Development • Reactive Extensions (Rx) for. NET • Available for. NET 3. 5 SP 1 &. NET 4 • Silverlight 3 & 4 • Requires Visual Studio 2008 SP 1 or 2010 • Reactive Extensions for Java. Script • • Can be used by any web page Interfaces with a number of other Java. Script Libraries Presentation and Samples - http: //cwa. me. uk/Reactive 4
What is it all about? “Reactive programming is a programming paradigm oriented around data flows and the propagation of change” – Wikipedia - http: //en. wikipedia. org/wiki/Reactive_programming Reactive Extensions (Rx) brings this style of programming to. NET and Java. Script • Powerful framework for working with events • Event Composition • Filtering • Push vs Pull programming 5
Before Reactive…Interactive Something we are familiar with: • Iterator Pattern • IEnumerable<T> and IEumerator<T> • Access aggregation of objects sequentially • LINQ to Objects 6
LINQ Recap • Language Integrated Query • Allows expressive statements to be made against objects and collections • IEnumerable Collections all support this since. NET 3. 5 • SQL like syntaxtic sugar, or more traditional chained method calls • LINQ to Objects: • from v in My. List where v. Property == 11 select new Foo(v); • My. List. Where(v => v. Property == 11). Select(v => new Foo(v)); 7
New bits for Interactive Programming • System. Interactive. Dll • Adds missing methods via IEnumerable. Ex class containing Extension Methods • • • Amb Buffer. With. Count Catch Concat Defer Delay Dematerialize Do Finally Generate Let • • • Materialize Max. By Memoize / Memoize. All Merge Min / Min. By On. Error. Resume. Next Prune Publish Remoteable Repeat • • • Replay Retry Run Scan Select. Many Share Starts. With Synchronise Throw Timeout Using 8
New bits for Interactive Programming • System. Interactive. Dll • Adds missing methods via IEnumerable. Ex class containing Extension Methods • • • Amb Buffer. With. Count Catch Concat Defer Delay Dematerialize Do Finally Generate Let • • • Materialize Max. By Memoize / Memoize. All Merge Min / Min. By On. Error. Resume. Next Prune Publish Remoteable Repeat • • • Replay Retry Run Scan Select. Many Share Starts. With Synchronise Throw Timeout Using 9
Demo 10
Going Reactive • System. Reactive. dll • Observable Collections & Events • LINQ to Events • Push rather than Pull • Subscribe vs Handling events 11
IObservable<T> & IObserver<T> • Core Interfaces of the Reactive Extensions, Part of the. NET 4 BCL • Located in System Namespace (mscorlib) • Observer subscribed to Observable to be notified of items • Dispose provides easy un-subscription 12
The Duality AKA ‘The science bit’ “a duality translates concepts, theorems or mathematical structures into other concepts, theorems or structures” - Wikipedia 13
Duality Continued public interface IEnumerator<T> : IDisposable { T Current { get; } // Can Throw Exception bool Move. Next(); } 14
Duality Continued public interface IEnumerator<T> : IDisposable { T Current { get; } // throws exception bool Move. Next(); } public interface IDual. Enumerator<T> { void Set. Current(T value | Exception ex); void Move. Next(bool can. Move); } 15
Duality Continued public interface IDual. Enumerator<T> { void Set. Current(T value | Exception ex); void Move. Next(bool can. Move); } public interface IDual. Enumerator<T> { void Yield(T value); void Throw(Exception ex); void Move. Next(bool can. Move); } 16
Duality Continued public interface IDual. Enumerator<T> { void Yield(T value); void Throw(Exception ex); void Move. Next(bool can. Move); } public interface IDual. Enumerator<T> { void Yield(T value); void Throw(Exception ex); void Break(); } 17
Duality Continued public interface IDual. Enumerator<T> { void Yield(T value); void Throw(Exception ex); void Break(); } public interface IObserver<T> { void On. Next(T value); void On. Error(Exception exception); void On. Completed(); } 18
IEnumerable to IObservable • Rx can use an underlying IEnumerable type as the source for an IObserverable Collection • T 0 Observable<T> Extension Method applies to all IEnumerable<T> • Wraps any IEnumerable <T> and provides IObservable interface • ‘Cold’ Observables 19
Demo 20
Other ways to make IObservables Helper methods offer ways of making IObservable instances • Empty • Return • Throw • Range • Concat • Repeat • Generate. With. Time • Can combine to make custom sequences. 21
Demo 22
. NET Event Handling (in C#) Recap Publishing Events public class My. Event. Source { public event Event. Handler<My. Event. Args> My. Event; } public class My. Event. Args : Event. Args { public object Value { get; private set; } public My. Event. Args(object val) { Value = val; } } 23
Event Handling (in C#) Recap Watching Events // Add handler my. Event. Source. My. Event += My. Event. Handler; // Remove handler my. Event. Source. My. Event -= My. Event. Handler; public void My. Event. Handler (object sender, My. Event. Args args) { //Handle } 24
Event Handling with IObservable • Observable of the IEvent Interface (Defined in System. Core. Ex. dll) • Easily created using helper method on Observable: Observable<IEvent<My. Event. Args>> = Observable. From. Event(my. Event. Source, “My. Event”); • Can then subscribe to events using the Subscribe method • Disposable feature of Observable handles Unsubscribe 25
Demo 26
Scheduler System. Concurrency. Scheduler (from System. Core. Ex. dll) • Many Rx Methods operate concurrently • Rx uses Parallel Framework for concurrency behaviours (Tasks) • Gives control over where actions take place • Several options: • • • Dispatcher Immediate New. Thread Task. Pool Thread. Pool • Set Scheduler using. Subscribe. On Method 27
Filtering Events • ‘LINQ to Events’ provides simple syntax to do powerful filtering of events • Event still occurs, we control our notification • . Where<T>(Func<IEvent<Event. Args. Type>, bool> predicate) 28
Demo 29
Composing Events • Lots of ways of combing events • Select. Many • Combine. Latest • Fork. Join • Zip • Join • & others mirroring the Interactive slide earlier All take multiple observable streams and combine into a single stream 30
Zip & Join Zip • Used to interleave events from one stream with that of another, combining the pairs. • Named as it behaves like a zipper Join • Allows combining streams of events using combinations of patterns. • Pattern constructed with And method, and values can be projected using Then Photos: //Amy// @ Flickr - http: //www. flickr. com/photos/_-amy-_/3528810363/ Zimpenfish @ Flickr - http: //www. flickr. com/photos/zimpenfish/131281018 / 31
Demo 32
Aggregations • Observables can be aggregated using a selection of built in aggregation functions: • • • Aggregate Any All Contains Count • • • Sum Average Last Min/Min. By Max/Max. By 33
Asynchronous Programming • Motivated by moving to the cloud • View asynchronous operations as a push collection of event • Error handlings, timeouts all supported • Can convert any function to Async Observable using. To. Async() • Then subscribe, and receive notification when method returns • Non-Blocking 34
Demo 35
Reactive Extensions for Java. Script • Implementation for Java. Script very similar • Full IObservable / IObserver implementation • Does most of what Rx for. NET does • Brings some LINQ like functionality • Integration with lots of common Java. Script libraries: • • • j. Query Dojo extjs Moo. Tools Prototype YUI 3 36
Native Java. Script Integration • rx. Html. js • Can create observables using Rx. Observable. From. Html. Event 37
j. Query & Other libraries • rx. jquery. js • Extends j. Query to add helpers for Rx functionality: • to. Observable() • Adds Observable versions of common j. Query functions: • fade. In. As. Observable(duration) • fade. To. As. Observable(duration, opacity) • j. Query Events integration, includes Live Events 38
Summary • Great library which brings a whole new way of working with events • Vital in a cloud based world • Still under active development • New things being added • Breaking changes do happen • Reactive Extensions for Java. Script not just for. NET Devs • Pure Javascript • Easy way of combing 39
Resources Dev. Labs Project Page – http: //tinyurl. com/reactive. Extensions Reactive Extensions Team Blog – http: //blogs. msdn. com/b/rxteam Mathew Podwysocki’s Blog - http: //weblogs. asp. net/podwysocki/ Bart de Smet’s Blog - http: //community. bartdesmet. net Channel 9 – http: //www. channel 9. com Slides and Demos - http: //cwa. me. uk/talks/reactive 40
41