don’t be passive, be reactive
DESCRIPTION
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 - PowerPoint PPT PresentationTRANSCRIPT
An introduction to the Reactive Extensions for .NET and JavaScript
Chris Alcock
DeveloperDeveloperDeveloper South West 2010
• 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: [email protected]
Twitter: @calcock
Personal Blog: http://cwa.me.uk
About Me
• 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
Agenda
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
Getting the bits…
“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
What is it all about?
Something we are familiar with:
•Iterator Pattern
•IEnumerable<T> and IEumerator<T>
•Access aggregation of objects sequentially
•LINQ to Objects
Before Reactive…Interactive
• 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 MyList where v.Property == 11 select new Foo(v);
• MyList.Where(v => v.Property == 11).Select(v => new Foo(v));
LINQ Recap
• System.Interactive.Dll
• Adds missing methods via IEnumerableEx class containing Extension Methods
New bits for Interactive Programming
• Amb• BufferWithCoun
t• Catch• Concat• Defer• Delay• Dematerialize• Do• Finally• Generate• Let
• Materialize• Max MaxBy• Memoize /
MemoizeAll• Merge• Min / MinBy• OnErrorResumeN
ext• Prune• Publish• Remoteable• Repeat
• Replay• Retry• Run• Scan• SelectMany• Share• StartsWith• Synchronise• Throw• Timeout• Using
• System.Interactive.Dll
• Adds missing methods via IEnumerableEx class containing Extension Methods
New bits for Interactive Programming
Demo
• System.Reactive.dll
• Observable Collections & Events
• LINQ to Events
• Push rather than Pull
• Subscribe vs Handling events
Going Reactive
• 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
IObservable<T> & IObserver<T>
AKA ‘The science bit’
“a duality translates concepts, theorems or mathematical
structures into other concepts, theorems or structures”
- Wikipedia
The Duality
public interface IEnumerator<T> : IDisposable{
T Current { get; } // Can Throw Exceptionbool MoveNext();
}
Duality Continued
Duality Continued
public interface IDualEnumerator<T>{
void SetCurrent(T value | Exception ex);void MoveNext(bool canMove);
}
Duality Continued
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 Break();
}
Duality Continued
public interface IObserver<T>{
void OnNext(T value);void OnError(Exception exception);void OnCompleted();
}
• 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 to IObservable
Demo
Helper methods offer ways of making IObservable instances• Empty
• Return
• Throw
• Range
• Concat
• Repeat
• Generate
• GenerateWithTime
•Can combine to make custom sequences.
Other ways to make IObservables
Demo
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; }
}
.NET Event Handling (in C#) Recap
Watching Events
// Add handler
myEventSource.MyEvent += MyEventHandler;
// Remove handler
myEventSource.MyEvent -= MyEventHandler;
public void MyEventHandler (object sender, MyEventArgs args) {
//Handle
}
Event Handling (in C#) Recap
• 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
Event Handling with IObservable
Demo
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
Scheduler
• ‘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
• 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
Composing Events
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 ThenPhotos: //Amy// @ Flickr - http://www.flickr.com/photos/_-amy-_/3528810363/Zimpenfish @ Flickr - http://www.flickr.com/photos/zimpenfish/131281018/
Zip & Join
Demo
• Observables can be aggregated using a selection of built in aggregation functions:
Aggregations
• Sum • Average • Last• Min/MinBy • Max/MaxBy
• Aggregate • Any • All • Contains • Count
• 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
Asynchronous Programming
Demo
• 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
Reactive Extensions for JavaScript
• rx.Html.js
• Can create observables using Rx.Observable.FromHtmlEvent
Native JavaScript Integration
• 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
jQuery & Other libraries
• 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
Summary
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
Resources