410 likes | 672 Views
Don’t be passive, be Reactive. An introduction to the Reactive Extensions for .NET and JavaScript Chris Alcock. DeveloperDeveloperDeveloper South West 2010. About Me. First time Conference Speaker Based in Liverpool, UK Software Developer using .NET stack @ New Mind 2010 ASP.NET MVP
E N D
Don’t be passive, be Reactive An introduction to the Reactive Extensions for .NET and JavaScript Chris Alcock DeveloperDeveloperDeveloper 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 uphttp://TheMorningBrew.Net • Email: calcock@incanus.co.uk • Twitter: @calcock • Personal Blog: http://cwa.me.uk
Agenda • What is Reactive / Interactive? • How do we get to Reactive? • Reactive Extensions in C# • Events • IEnumerable • LINQ • Asynchronous Operations • Reactive Extensions for JavaScript, jQuery Integration
Getting the bits… • Available from Microsoft DevLabs • http://tinyurl.com/ReactiveExtensions • Under Active Development • Reactive Extensions (Rx) for .NET • Available for .NET 3.5 SP1 & .NET4 • Silverlight 3 & 4 • Requires Visual Studio 2008 SP1 or 2010 • Reactive Extensions for JavaScript • Can be used by any web page • Interfaces with a number of other JavaScript Libraries • Presentation and Samples - http://cwa.me.uk/Reactive
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 JavaScript • Powerful framework for working with events • Event Composition • Filtering • Push vs Pull programming
Before Reactive…Interactive • Something we are familiar with: • Iterator Pattern • IEnumerable<T> and IEumerator<T> • Access aggregation of objects sequentially • LINQ to Objects
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 inMyListwherev.Property == 11 select new Foo(v); • MyList.Where(v => v.Property == 11).Select(v => new Foo(v));
New bits for Interactive Programming • System.Interactive.Dll • Adds missing methods via IEnumerableEx class containing Extension Methods • Amb • BufferWithCount • Catch • Concat • Defer • Delay • Dematerialize • Do • Finally • Generate • Let • Materialize • Max MaxBy • Memoize / MemoizeAll • Merge • Min / MinBy • OnErrorResumeNext • Prune • Publish • Remoteable • Repeat • Replay • Retry • Run • Scan • SelectMany • Share • StartsWith • Synchronise • Throw • Timeout • Using
New bits for Interactive Programming • System.Interactive.Dll • Adds missing methods via IEnumerableEx class containing Extension Methods • Amb • BufferWithCount • Catch • Concat • Defer • Delay • Dematerialize • Do • Finally • Generate • Let • Materialize • Max MaxBy • Memoize / MemoizeAll • Merge • Min / MinBy • OnErrorResumeNext • Prune • Publish • Remoteable • Repeat • Replay • Retry • Run • Scan • SelectMany • Share • StartsWith • Synchronise • Throw • Timeout • Using
Going Reactive • System.Reactive.dll • Observable Collections & Events • LINQ to Events • Push rather than Pull • Subscribe vs Handling events
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
The Duality • AKA ‘The science bit’ • “a duality translates concepts, theorems or mathematical structures into other concepts, theorems or structures” • - Wikipedia
Duality Continued • public interface IEnumerator<T> : IDisposable{ T Current { get; } // Can Throw Exception bool MoveNext();}
Duality Continued • public interface IEnumerator<T> : IDisposable{ T Current { get; } // throws exception bool MoveNext();} public interface IDualEnumerator<T>{ void SetCurrent(T value | Exception ex); void MoveNext(bool canMove);}
Duality Continued • public interface IDualEnumerator<T>{ void SetCurrent(T value | Exception ex); void MoveNext(bool canMove);} public interface IDualEnumerator<T>{ void Yield(T value); void Throw(Exception ex); void MoveNext(bool canMove);}
Duality Continued • public interface IDualEnumerator<T>{ void Yield(T value); void Throw(Exception ex); void MoveNext(bool canMove);} public interface IDualEnumerator<T>{ void Yield(T value); void Throw(Exception ex); void Break();}
Duality Continued • public interface IDualEnumerator<T>{ void Yield(T value); void Throw(Exception ex); void Break();} public interface IObserver<T>{ void OnNext(T value); void OnError(Exception exception); void OnCompleted();}
IEnumerable to IObservable • Rx can use an underlying IEnumerable type as the source for an IObserverable Collection • T0Observable<T> Extension Method applies to all IEnumerable<T> • Wraps any IEnumerable <T> and provides IObservable interface • ‘Cold’ Observables
IEnumerable Demo
Other ways to make IObservables • Helper methods offer ways of making IObservable instances • Empty • Return • Throw • Range • Concat • Repeat • Generate • GenerateWithTime • Can combine to make custom sequences.
.NET Event Handling (in C#) Recap • Publishing Events • public class MyEventSource { • public event EventHandler<MyEventArgs> MyEvent; • } • public class MyEventArgs : EventArgs{ • public object Value { get; private set; } • public MyEventArgs(object val) { Value = val; } • }
Event Handling (in C#) Recap • Watching Events • // Add handler • myEventSource.MyEvent+= MyEventHandler; • // Remove handler • myEventSource.MyEvent-= MyEventHandler; • public void MyEventHandler (object sender, MyEventArgsargs){ • //Handle • }
Event Handling with IObservable • Observable of the IEvent Interface (Defined in System.CoreEx.dll) • Easily created using helper method on Observable: • Observable<IEvent<MyEventArgs>> • = Observable.FromEvent(myEventSource, “MyEvent”); • Can then subscribe to events using the Subscribe method • Disposable feature of Observable handles Unsubscribe
Reactive Events Demo
Scheduler • System.Concurrency.Scheduler (from System.CoreEx.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 • NewThread • TaskPool • ThreadPool • Set Scheduler using .SubscribeOn Method
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<EventArgsType>, bool> predicate)
Filtering Events Demo
Composing Events • Lots of ways of combing events • SelectMany • CombineLatest • ForkJoin • Zip • Join • & others mirroring the Interactive slide earlier • All take multiple observable streams and combine into a single stream
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/
Zip and Join Demo
Aggregations • Observables can be aggregated using a selection of built in aggregation functions: • Aggregate • Any • All • Contains • Count • Sum • Average • Last • Min/MinBy • Max/MaxBy
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 .ToAsync() • Then subscribe, and receive notification when method returns • Non-Blocking
Async in C# Demo
Reactive Extensions for JavaScript • Implementation for JavaScript very similar • Full IObservable / IObserver implementation • Does most of what Rx for .NET does • Brings some LINQ like functionality • Integration with lots of common JavaScript libraries: • jQuery • Dojo • extjs • MooTools • Prototype • YUI3
Native JavaScript Integration • rx.Html.js • Can create observables using Rx.Observable.FromHtmlEvent
jQuery & Other libraries • rx.jquery.js • Extends jQuery to add helpers for Rx functionality: • toObservable() • Adds Observable versions of common jQuery functions: • fadeInAsObservable(duration) • fadeToAsObservable(duration, opacity) • jQuery Events integration, includes Live Events
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 JavaScript not just for .NET Devs • Pure Javascript • Easy way of combing
Resources • DevLabs Project Page – http://tinyurl.com/reactiveExtensions • 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.channel9.com • Slides and Demos - http://cwa.me.uk/talks/reactive