Mini training - Reactive Extensions (Rx)

Post on 16-Apr-2017

835 views 6 download

Transcript of Mini training - Reactive Extensions (Rx)

MAXIME LEMAITRE – 23/12/2015

Reactive Extensionsbuzzs.Filter(IsAwesome).Subscribe(s=> {levelup++;})

Agenda

• Introduction• Reactive Programming• Reactive Extensions• Rx.Net• Examples• Question

Reactive Extensions aka Rx, origninally Crafted by Microsoft in 2009

What is Reactive Programming ?

Reactive programming is programming of asynchonous data streams.

More definitions : Wikipedia, Stackoverflow, Reactive Manifesto, Microsoft

A responsive application is the goal.

A responsive application is both scalable and resilient. Responsiveness is impossible to achieve without both scalability and resilience.

A message-driven architecture is the foundation of scalable, resilient, and ultimately responsive systems.

What is a Stream ?

• A Stream is a Sequence of items in a particular order that may or may not end

• It can emit three different things: – a value (of some type), – an error– "completed" signal. All these events can be asynchronous

• A list/collection can be seen as a stream– Determinist– Ended

Streams are everywhere

anything can be a stream: events, variables, user inputs,

properties, caches, data structures, etc.

What are Reactive Extensions (Rx)?

• The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators.

• It provides a collection of operators with which you can filter, select, transform, combine, and compose Observables. This allows for efficient execution and composition.

• From Pull Model => Iterable (Iterator Pattern) to Push Model => Observable (Observer Pattern)

Pull vs Push Models

Better codebases

Rx is everywhere

• Rx is available in most programming languages– Java: RxJava– JavaScript: RxJS– C#: Rx.NET– C#(Unity): UniRx– Scala: RxScala– Clojure: RxClojure– C++: RxCpp– Ruby: Rx.rb– Python: RxPY– Groovy: RxGroovy– JRuby: RxJRuby– Kotlin: RxKotlin– Swift: RxSwift

“The desktop developers at GitHub loved Rx so much, that the Mac team created their own version of Rx and ReactiveUI, called ReactiveCocoa, and are now using it on the Mac to obtain similar benefits.” – Paul Betts, GitHub

Rx Operators• Creating Observables

– Create, Defer, Empty/Never/Throw, From , Interval, Just, Range, Repeat, Start, Timer• Transforming Observables

– Buffer, FlatMap, GroupBy, Map, Scan, Window• Filtering Observables

– Debounce, Distinct, ElementAt, Filter, First, IgnoreElements, Last, Sample, Skip, SkipLast, Take, TakeLast

• Combining Observables– And/Then/When, CombineLatest, Join, Merge, StartWith, Switch, Zip

• Error Handling Operators– Catch, Retry

• Observable Utility Operators– Delay, Do, Materialize/Dematerialize, ObserveOn, Serialize, Subscribe, SubscribeOn,

TimeInterval, Timeout, Timestamp, Using• Conditional and Boolean Operators

– All, Amb, Contains, DefaultIfEmpty, SequenceEqual, SkipUntil, SkipWhile, TakeUntil, TakeWhile• Mathematical and Aggregate Operators

– Average, Concat, Count, Max, Min, Reduce, Sum • Connectable Observable Operators, …

Understand Operators with Marble Diagramshttp://rxmarbles.com/

Rx.Net

Rx is …1. a set of types representing asynchronous data streams2. a set of operators to query asynchronous data streams3. a set of types to parameterize concurrency

Rx = Observables + LINQ + Schedulers

IObservable, IObserverPart of .NET 4

How to create observables in Rx.Net ?• Factory Methods

– Observable.Return– Observable.Empty– Observable.Never– Observable.Throw– Observable.Create

• Unfold methods– Observable.Range– Observable.Interval– Observable.Timer– Observable.Generate

• Paradigm Transition– Observable.Start– Observable.FromEventPattern– Task.ToObservable– Task<T>.ToObservable– IEnumerable<T>.ToObservable– Observable.FromAsyncPattern

Example #1 : Event Processing

MSFT27.01

INTC21.75

MSFT27.96

MSFT31.21

INTC22.54

INTC20.98

MSFT30.73

Given: Stream of stock ticksFind: 10% daily price increase

Example #1 : Event Processing

from tick in stockTicks

group tick by tick.Symbol into symbolStream

from window in symbolStream.Buffer(2, 1)

let increase = PriceIncrease(window)

where increase > .1

select new { symbol = symbolStream.Key, increase };

Source (Observable)

group

aggregate

apply

filter

reduce

Use case #2 : AutoComplete TextBox (RxJs)

Common Problems : Too many requests on the servers, bad user experience, sluggy animations, error handling, duplicated requests …

Use case #2 : AutoComplete TextBox (RxJs)

Full code https://github.com/Reactive-Extensions/RxJS/tree/master/examples/autocomplete

1 – Search function3 – Subscribe

2 – Composition

Example#3 : Monitoring

• Day 0 – 1 Client– Used for one features

• Day N – X Clients (X >>1)– Used everywhere– New features on API side

incr Hit

Update Node

Update Metrics

a few commands/min

a few 10 000s/secs

Example#3 : Monitoring

• Basic idea : Buffer commands increment Hit every 5 secs

Update Node every 500 hits

Update Metrics once/minute

Quizz

• What’s the difference between Rx and databinding ?

• Should I have to use Rx since .net 4.5 (await/async) ?

• Where is Rx appropriate ?• Should I have to create my own

observables/observers ?• How do manage UI/main

thread/multithreading with ReactiveX ?• ….

Questions

References

• https://gist.github.com/staltz/868e7e9bc2a7b8c1f754• http://www.introtorx.com/• http://reactivex.io/• https://github.com/Reactive-Extensions• https://blog.xamarin.com/why-every-mobile-developer-should-use-reactive-programming/• https://vimeo.com/43659034• https://github.com/kriskowal/gtor • https://www.youtube.com/watch?v=5DZ8nC0ENdg • http://futurice.com/blog/reactive-c-number-in-practice • http://rxwiki.wikidot.com/101samples • https://medium.com/reactive-programming/what-is-reactive-programming-bc9fa7f4a7fc#.x0tnt96i4

About Us• Betclic Everest Group, one of the world leaders in online

gaming, has a unique portfolio comprising various complementary international brands: Betclic, Everest Poker/Casino, Bet-at-home, Expekt, Imperial Casino, Monte-Carlo Casino…

• Through our brands, Betclic Everest Group places expertise, technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players. We want our brands to be easy to use for every gamer around the world. We’re building our company to make that happen.

• Active in 100 countries with more than 12 million customers worldwide, the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association).

We want our Sports betting, Poker, Horse racing and Casino & Games brands to be easy to use for every gamer around the world. Code with us to make that happen.

Look at all the challenges we offer HERE

Check our Employer Page

Follow us on LinkedIn

WE’RE HIRING !