Introduction to Reactive Extensions

Post on 09-May-2015

1.301 views 4 download

description

An introduction to the Reactive Extensions (Rx) framework by Microsoft. Rx provides a simpler event model for handling streams of events in asynchronous and event based programs

Transcript of Introduction to Reactive Extensions

Introduction to Reactive Extensions

1

An Introduction to Reactive Extensions

Peter Goodman

Introduction to Reactive Extensions

2

What are Reactive Extensions?Rx is a library for composing asynchronous and event-based programs using observable collections.

Introduction to Reactive Extensions

3

What are Reactive Extensions?Rx is a library for composing asynchronous and event-based programs using observable collections.

Introduction to Reactive Extensions

4

What are Reactive Extensions?Rx is a library for composing asynchronous and event-based programs using observable collections.

Introduction to Reactive Extensions

5

What are Reactive Extensions?Rx is a library for composing asynchronous and event-based programs using observable collections.

Introduction to Reactive Extensions

6

Events in .Net

form1.MouseMove += (sender, args) => {

if (args.Location.X == args.Location.Y) // I’d like to raise another event};

form1.MouseMove -= /* what goes here? */

Not first class

Awkward syntax, resource maintenance

Not composable

Introduction to Reactive Extensions

7

interface IEnumerable<out T>{ IEnumerator<T> GetEnumerator();}

interface IEnumerator<out T> : IDisposable{ bool MoveNext(); T Current { get; } void Reset();}

Collections are Enumerables

Blocking

PULL

Introduction to Reactive Extensions

8

What if events were collections? Collection

Event Stream

TIME

Move Next Move Next Move Next Move Next Move NextMove Next

OnNext OnNext OnNext OnNext OnNext OnNext

Introduction to Reactive Extensions

9

Observables

interface IObservable<out T>{ IDisposable Subscribe(IObserver<T> observer);}

interface IObserver<in T>{ void OnNext(T value); void OnError(Exception ex); void OnCompleted();}

PUSHPush the next value

An Error occurred!

We’re done!

Introduction to Reactive Extensions

10

Summary Push vs Pull

Environment

Mo

veN

ext

Got next?

Application

On

Next Have next!

IEnumerable<T>IEnumerator<T>

IObservable<T>IObserver<T>

Inte

ract

ive R

eactive

Introduction to Reactive Extensions

11

Creating Observables - Primitive

Observable.Empty<int>()

Observable.Return(42)

Observable.Throw<int>(ex)

OnCompleted

OnNext

OnError

Observable.Never<int>()

new int[0]

new[] { 42 }

Throwing iterator

Iterator that got stuckNotion of time

Introduction to Reactive Extensions

12

Creating Observables - Range

Observable.Range(0, 3)

OnNext(0)

OnNext(1)

OnNext(2)

Enumerable.Range(0, 3)

yield 0 yield 1 yield 2

Introduction to Reactive Extensions

13Generating values and Subscribing

o = Observable.Generate( 0, i => i < 10, i => i + 1, i => i * i);

o.Subscribe(x => { Console.WriteLine(x);});

e = new IEnumerable<int> { for (int i = 0; i < 10; i++) yield return i * i;};

foreach (var x in e) { Console.WriteLine(x);}

Hypothetical anonymous iterator

syntax in C#

Synchronous

Asynchronous

A variant with time notion exists

(GenerateWithTime)

Introduction to Reactive Extensions

14

IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted();});

IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); });

Subscribing

Introduction to Reactive Extensions

DEMOGenerating events and subscribing to them

15

Introduction to Reactive Extensions

16

Observable Querying Observables are sources of data

Data is sent to you (push based) Extra (optional) notion of time.

Hence we can query over them

// Producing an IObservable<Point> using Selectvar mme = from mm in Observable.FromEvent<MouseEventArgs>( form, “MouseMove”) select mm.EventArgs.Location;

// Filtering for the first bisector using Wherevar res = from mm in mme where mm.X == mm.Y select mm;

Introduction to Reactive Extensions

DEMOQuerying, Composition and introducing Concurrency

17

Introduction to Reactive Extensions

18

Introducing Asynchrony

An Asynchronous operation can be thought of as an Observable that returns a single value and completes.

FromAsync Takes an APM method pair (BeginExecute, EndExecute) and

creates an Observable

ToAsync Takes a method and creates an Observable (Like TPL)

Introduction to Reactive Extensions

19

Introducing Concurrency

Many operators in Rx introduce Concurrency Throttle Interval Delay BufferWithTime

Generally they provide an overload to supply a Scheduler ImmediateScheduler – Static Immediate CurrentThreadScheduler – Placed on a queue for the current thread NewThreadScheduler – Spawn a new Thread DispatcherScheduler - Silverlight TaskPoolScheduler - TPL ThreadPoolScheduler

Introduction to Reactive Extensions

20

Concurrency and Synchronization

• IScheduler• WPF dispatcher• WinForms control• SynchronizationCont

ext

• How to synchronize?

• Compositionality to the rescue!

var xs = Observable.Return(42, Scheduler.ThreadPool);xs.Subscribe(x => lbl.Text = "Answer = " + x);

xs.ObserveOnDispatcher().Subscribe(x => lbl.Text = "Answer = " + x);

Introduction to Reactive Extensions

DEMOSynchronization

21

Introduction to Reactive Extensions

Rx for JavaScript (RxJS)

Parity with Rx for .NET Set of operators Taming asynchronous JS

JavaScript-specific bindings jQuery ExtJS Dojo Prototype YUI3 MooTools Bing APIs

22

23

Introduction to Reactive Extensions

DEMORx for JavaScript

Introduction to Reactive Extensions

24

Questions?Reactive Extensions

Introduction to Reactive Extensions

25

Resources MSDN

Bart de Smet / Rx (Channel 9)

Reactive UI

Pushqa / SignalR

Introduction to Reactive Extensions

26

Contact pete@petegoo.com

http://blog.petegoo.com

Twitter: @petegoo