Reactive Extensions .NET

21
Verisk Insurance Solutions | ISO AIR Worldwide Xactware © 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary A not-comprehensive introduction. February 8, 2016 1 Reactive Extensions .NET George Taskos

Transcript of Reactive Extensions .NET

Page 1: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

A not-comprehensive introduction.February 8, 2016

1

Reactive Extensions .NET

George Taskos

Page 2: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

2

“Functional programming allows developers to describe what they want to do, rather than

forcing them to describe how they want to do it.”

Anders Hejlsberg, C# Creator

Page 3: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

3

So, what is it?

Page 4: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

4

Everybody loves RxLanguages• Java: RxJava (NETFLIX, used for server-side concurrency) • JavaScript: RxJS (Autocomplete, drag&drop, animation, etc.)• C#(Unity): UniRx• Scala: RxScala• Clojure: RxClojure• C++: RxCpp• Ruby: Rx.rb• Python: RxPY• Groovy: RxGroovy• JRuby: RxJRuby• Kotlin: RxKotlin• Swift: RxSwift

ReactiveX for platforms and frameworks• RxNetty• RxAndroid• RxCocoa• RxUI

Page 5: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

5

Why?• Parallel programming with .NET is tricky

• Error Handling

• Cancellation

• Easy scheduling (timeout, throttling)

• Easier to test

Page 6: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

6

Sequences ARE COOL• Sequences are a list of things, in a particular order, that may or may not end

• In C#, one very common sequence is IEnumerable<T>

• Sequences are lazy

Page 7: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

7

var thisDoesntTakeAnyTimeAtAll = Enumerable.Range(0, 100000)

.Select(x => { Thread.Sleep(1000); return x*5; });

Console.WriteLine(”This happens instantly!”);

Page 8: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

8

Events in .NETthis.KeyUp += (sender, args) => { /* Act on this event. I want to combine with another one, so difficult to compose events! */}

this.KeyUp -= /* Nope, anonymous handlers cannot be cleaned */

• Resource management? OMG! • Events are just weird, and definitely NOT cool

Page 9: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

9

More about events (not cool!)• Events show up everywhere in .NET

• Events are not compositional

• var thatEvent = myButton.Clicked;

>> V>> e

textBox.KeyUp += (o, e) => { Console.WriteLine(e.Char); } >> r

>> i>> s>> k

Page 10: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

10

• Hmmm…”Sequences are a list of things, in a particular order, that may or may not end.”, is that like events?

Better events?

// Try this with events

IObservable<string> userTypedVerisk = textBox.KeyUp.Buffer(5 /*items*/, 1 /*at a time*/).Select(x => String.Join(x)) /* Join every 5 chars */.Where(x => x.Equals(“Verisk”)); /* Check equality */

Page 11: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

11

Collections in .NETinterface IEnumerable<out T>{

IEnumerator<T> GetEnumerator();}

interface IEnumerator<out T> : IDisposable{

bool MoveNext(); T Current { get; } void Reset();

}

Page 12: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

12

Reactive observable streamspublic interface IObservable<out T> {

IDisposable Subscribe(IObserver<T> observer); }

public interface IObserver<in T> {

void OnNext(T value); // Next valuevoid OnError(Exception error); // Oops! Error!void OnCompleted(); // That’s all folks

}

Page 13: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

13

Pull enumerable values (give me what you have)

• In memory collections • Database queries • Generated sequences • Message queues• …

Push to subscriber (don’t call me, I will call you)

• Event streams • Asynchronous computations • Asynchronous queries • Asynchronous enumerations• …

Page 14: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

14

How do you create observables?

• From arrays

• From a single value

• From .NET Events

• From Tasks

• Manually, using Subject<T>

Page 15: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

15

Composability

• LINQ (Where, Take, Skip, Sum, Max, Any, …)• Statements (If, Case, For, While, DoWhile)• Combinators (Merge, Zip, Amb, …)• Exceptions (Catch, Retry, ...)• Rx (Delay, Throttle, Interval, Publish, ...)

Page 16: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

16

LINQ is our superhero!

// Hot, will return results on subscribe, we set it up and will // evaluate when we asked for the valuesvar openOrdersObservable = context.Orders

.Where(o => o.UserId == userId && o.Status ==

OrderStatus.Open).Take(100).ToObservable();

// Subscribe is your foreach, I’ll let you know the results nowIDisposable openOrdersSubscription = openOrdersObservable

.Subscribe(orders => /* Do stuff */);

// Clean up when you need, ah, disposable!openOrdersSubscription.Dispose()

Page 17: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

17

ConcurrencyMany 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

Page 18: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

18

Synchronization

var observable= Observable.Return(“Hello Rx”, Scheduler.ThreadPool);

/* Cross-thread operation, not valid */observable.Subscribe(p => label.Text = p);

/* No problem, we got this */observable.ObserveOn (RxApp.MainThreadScheduler).Subscribe(p => label.Text = p);

Page 19: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

19

ReactiveUI

• A MVVM framework that integrates with the Reactive Extensions for .NET to create elegant, testable User Interfaces that run on any mobile or desktop platform

Page 20: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

20

Resources

• ReactiveX - http://reactivex.io/• ReactiveUI - http://reactiveui.net/• Beginner’s Guide to the Rx - http://bit.ly/1O0mFl0• The Reactive Manifesto - http://bit.ly/1tw0qgj

• Intro to Rx - http://www.introtorx.com/• Programming Rx & LINQ - http://bit.ly/1K8u3jA

• Demo source code - http://bit.ly/1nTQ3nG

Page 21: Reactive Extensions .NET

Verisk Insurance Solutions | ISO AIR Worldwide Xactware© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary© 2015 Verisk Analytics, Inc. All rights reserved. Confidential and Proprietary

Demo

Let’s be Reactive!