1 / 41

Don’t be passive, be Reactive

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

maeko
Download Presentation

Don’t be passive, be Reactive

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Don’t be passive, be Reactive An introduction to the Reactive Extensions for .NET and JavaScript Chris Alcock DeveloperDeveloperDeveloper South West 2010

  2. 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

  3. 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

  4. 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

  5. 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

  6. Before Reactive…Interactive • Something we are familiar with: • Iterator Pattern • IEnumerable<T> and IEumerator<T> • Access aggregation of objects sequentially • LINQ to Objects

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

  8. 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

  9. 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

  10. Interactive Programming Demo

  11. Going Reactive • System.Reactive.dll • Observable Collections & Events • LINQ to Events • Push rather than Pull • Subscribe vs Handling events

  12. 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

  13. The Duality • AKA ‘The science bit’ • “a duality translates concepts, theorems or mathematical structures into other concepts, theorems or structures” • - Wikipedia

  14. Duality Continued • public interface IEnumerator<T> : IDisposable{ T Current { get; } // Can Throw Exception bool MoveNext();}

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

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

  17. 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();}

  18. 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();}

  19. 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

  20. IEnumerable Demo

  21. 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.

  22. Observable Generation Demo

  23. .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; } • }

  24. Event Handling (in C#) Recap • Watching Events • // Add handler • myEventSource.MyEvent+= MyEventHandler; • // Remove handler • myEventSource.MyEvent-= MyEventHandler; • public void MyEventHandler (object sender, MyEventArgsargs){ • //Handle • }

  25. 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

  26. Reactive Events Demo

  27. 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

  28. 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)

  29. Filtering Events Demo

  30. 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

  31. 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/

  32. Zip and Join Demo

  33. 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

  34. 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

  35. Async in C# Demo

  36. 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

  37. Native JavaScript Integration • rx.Html.js • Can create observables using Rx.Observable.FromHtmlEvent

  38. 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

  39. 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

  40. 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

More Related