don’t be passive, be reactive

41
An introduction to the Reactive Extensions for .NET and JavaScript Chris Alcock DeveloperDeveloperDeveloper South West 2010

Upload: maeko

Post on 16-Jan-2016

88 views

Category:

Documents


0 download

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 Presentation

TRANSCRIPT

Page 1: Don’t be passive, be Reactive

An introduction to the Reactive Extensions for .NET and JavaScript

Chris Alcock

DeveloperDeveloperDeveloper South West 2010

Page 2: Don’t be passive, be Reactive

• 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

Page 3: Don’t be passive, be Reactive

• 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

Page 4: Don’t be passive, be Reactive

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…

Page 5: Don’t be passive, be Reactive

“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?

Page 6: Don’t be passive, be Reactive

Something we are familiar with:

•Iterator Pattern

•IEnumerable<T> and IEumerator<T>

•Access aggregation of objects sequentially

•LINQ to Objects

Before Reactive…Interactive

Page 7: Don’t be passive, be Reactive

• 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

Page 8: Don’t be passive, be Reactive

• 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

Page 9: Don’t be passive, be Reactive

• System.Interactive.Dll

• Adds missing methods via IEnumerableEx class containing Extension Methods

New bits for Interactive Programming

Page 10: Don’t be passive, be Reactive

Demo

Page 11: Don’t be passive, be Reactive

• System.Reactive.dll

• Observable Collections & Events

• LINQ to Events

• Push rather than Pull

• Subscribe vs Handling events

Going Reactive

Page 12: Don’t be passive, be 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>

Page 13: Don’t be passive, be Reactive

AKA ‘The science bit’

“a duality translates concepts, theorems or mathematical

structures into other concepts, theorems or structures”

- Wikipedia

The Duality

Page 14: Don’t be passive, be Reactive

public interface IEnumerator<T> : IDisposable{

T Current { get; } // Can Throw Exceptionbool MoveNext();

}

Duality Continued

Page 15: Don’t be passive, be Reactive

Duality Continued

public interface IDualEnumerator<T>{

void SetCurrent(T value | Exception ex);void MoveNext(bool canMove);

}

Page 16: Don’t be passive, be Reactive

Duality Continued

public interface IDualEnumerator<T>{

void Yield(T value);void Throw(Exception ex);

void MoveNext(bool canMove);}

Page 17: Don’t be passive, be Reactive

Duality Continued

public interface IDualEnumerator<T>{

void Yield(T value);void Throw(Exception ex);void Break();

}

Page 18: Don’t be passive, be Reactive

Duality Continued

public interface IObserver<T>{

void OnNext(T value);void OnError(Exception exception);void OnCompleted();

}

Page 19: Don’t be passive, be Reactive

• 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

Page 20: Don’t be passive, be Reactive

Demo

Page 21: Don’t be passive, be Reactive

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

Page 22: Don’t be passive, be Reactive

Demo

Page 23: Don’t be passive, be Reactive

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

Page 24: Don’t be passive, be Reactive

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

Page 25: Don’t be passive, be Reactive

• 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

Page 26: Don’t be passive, be Reactive

Demo

Page 27: Don’t be passive, be Reactive

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

Page 28: Don’t be passive, be Reactive

• ‘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

Page 29: Don’t be passive, be Reactive

Demo

Page 30: Don’t be passive, be Reactive

• 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

Page 31: Don’t be passive, be Reactive

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

Page 32: Don’t be passive, be Reactive

Demo

Page 33: Don’t be passive, be Reactive

• 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

Page 34: Don’t be passive, be Reactive

• 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

Page 35: Don’t be passive, be Reactive

Demo

Page 36: Don’t be passive, be Reactive

• 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

Page 37: Don’t be passive, be Reactive

• rx.Html.js

• Can create observables using Rx.Observable.FromHtmlEvent

Native JavaScript Integration

Page 38: Don’t be passive, be Reactive

• 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

Page 39: Don’t be passive, be Reactive

• 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

Page 40: Don’t be passive, be Reactive

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

Page 41: Don’t be passive, be Reactive