37
A Quick Intro to Rx Troy Miles 28 April 2016

A Quick Intro to ReactiveX

Embed Size (px)

Citation preview

Page 1: A Quick Intro to ReactiveX

A Quick Intro to RxTroy Miles 28 April 2016

Page 2: A Quick Intro to ReactiveX

Slides + Code

http://www.slideshare.net/rockncoder/a-quick-intro-to-reactivex

https://github.com/Rockncoder/rx-demos

Page 3: A Quick Intro to ReactiveX

AgendaQuick introduction

What are the Reactive Extensions (Rx)?

Why should I care?

How do I get started?

Summary

Page 4: A Quick Intro to ReactiveX

Troy MilesTroy Miles aka the RocknCoder

Over 36 years of programming experience

Speaker and author

Author of jQuery Essentials

[email protected]

@therockncoder

Page 5: A Quick Intro to ReactiveX

Upcoming talksAngular 2 Weekend Workshop - Los Angeles May 14th & 15th

Build a game in 60 minutes - IrvineMay 24th

SoCal Code Camp - San DiegoJune 25th & 26th

Cross Platform Game Programming - IrvineJuly 9th & 10th

Page 6: A Quick Intro to ReactiveX

What are the Reactive Extensions?

Page 7: A Quick Intro to ReactiveX

The life and death and rebirth of project Volta

Volta was an experimental .NET based toolset for building multi-tier web apps

2007 - Microsoft released it as a tech preview

2008 - the project was cancelled

2010 - the Reactive Extension were initial released

Rx was part of project Volta

Page 8: A Quick Intro to ReactiveX
Page 9: A Quick Intro to ReactiveX

Rx = Observables + LINQ + Schedulers

Page 10: A Quick Intro to ReactiveX

More definitions

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

An API for asynchronous stream programming

Page 11: A Quick Intro to ReactiveX
Page 12: A Quick Intro to ReactiveX

Observer

The observer pattern

Functions

onNext

onError

onCompleted

Page 13: A Quick Intro to ReactiveX

ObservableThe thing to watch

Functions called operators

Create

Filter

Aggregate

Perform

Handle errors

many more

Page 14: A Quick Intro to ReactiveX

Operators ‘o plentyAggregate

All

Amb

and_

And

Any

apply

as_blocking

AsObservable

AssertEqual

asyncAction

asyncFunc

Average

averageDouble

averageFloat

averageInteger

averageLong

blocking

Buffer

bufferWithCount

bufferWithTime

bufferWithTimeOrCount

byLine

cache

case

Cast

Catch

catchException

collect

collect (RxScala version of Filter)

CombineLatest

combineLatestWith

Concat

concat_all

concatMap

concatMapObserver

concatAll

concatWith

Connect

connect_forever

cons

Contains

Controlled

And over 300 more

Page 15: A Quick Intro to ReactiveX

Subscription

Ties the observer and observable together

Function

Subscribe

Dispose

Page 16: A Quick Intro to ReactiveX

Promise v Observable

Promise Observable

async helper yes yes

values single multiple

errors single multiple

cancellable no yes

retry no yes

Page 17: A Quick Intro to ReactiveX

Why should I care?

Page 18: A Quick Intro to ReactiveX

Time is money

Learning any new technology takes time

Your time is valuable

Is the dev community excited about it?

Will it help me do my current job?

Will it help me get my next job?

Page 19: A Quick Intro to ReactiveX

Who uses this stuff?

Page 20: A Quick Intro to ReactiveX
Page 21: A Quick Intro to ReactiveX

ThoughtWorks Tech Radar

The reactive architecture keeps spreading across platforms and paradigms simply because it solves a common problem in an elegant way, hiding inevitable application plumbing in a nice encapsulation.

Recommended for adoption July 2014

https://www.thoughtworks.com/radar/languages-and-frameworks/reactive-extensions-across-languages

Page 22: A Quick Intro to ReactiveX

Is it in my language?

Page 23: A Quick Intro to ReactiveX

Is it in my language?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

PHP: RxPHP

Page 24: A Quick Intro to ReactiveX

How do I get started?

Page 25: A Quick Intro to ReactiveX

The Observer

Rx works with collections that implement observer design pattern

This is the same observer described in the Gang of Four design pattern book

In C# it implements IQueryable which is an extension to IEnumerable used by LINQ

Page 26: A Quick Intro to ReactiveX

Collections, collections

In Rx, you begin with a collection and end with a collection

Rx methods, also called operators, always return a new collection and never mutate the passed collection

If you’ve ever have been exposed to a functional language like LISP, Scheme, Clojure or other this kind of pattern should be familiar

Page 27: A Quick Intro to ReactiveX

Rx.NET (C#)

Page 28: A Quick Intro to ReactiveX

Install Rx via NuGetRx-Main: The main package, often all you need

Includes

Rx-Core

Rx-Linq

Rx-Interfaces

Rx-PlatformServices

Page 29: A Quick Intro to ReactiveX

Other packagesRx-Providers: For creating expression trees

Rx-Xaml: UI Synchronization classes for XAML

Rx-Remoting: Adds extensions for .NET Remoting

Rx-WPF/RxWindowsStore

Rx-Test: For unit testing

Rx-Alias: Provides alias for some query operators

Page 30: A Quick Intro to ReactiveX

staticIEnumerable<string>EndlessBarrageOfEmail(){varrandom=newRandom();varemails=newList<String>{"Hereisanemail!",

"Anotheremail!","Yetanotheremail!"};

while(true){//Returnsomerandomemailsatrandomintervals.yieldreturnemails[random.Next(emails.Count)];Thread.Sleep(random.Next(1000));}}

Page 31: A Quick Intro to ReactiveX

staticvoidMain(){varmyInbox=EndlessBarrageOfEmail().ToObservable();

//Insteadofmakingyouwait5minutes,wewilljustcheckeverythreesecondsinstead.:)vargetMailEveryThreeSeconds=myInbox.Buffer(TimeSpan.FromSeconds(3));//Was.BufferWithTime(...

getMailEveryThreeSeconds.Subscribe(emails=>{Console.WriteLine("You'vegot{0}newmessages!Heretheyare!",emails.Count());foreach(varemailinemails){Console.WriteLine(">{0}",email);}Console.WriteLine();});

Console.ReadKey();}

Page 32: A Quick Intro to ReactiveX

RxJS (JavaScript)

Page 33: A Quick Intro to ReactiveX

Uses Wikipedia’s search service

Normally written using callbacks or promises

Written using ES2015, so it looks a bit weird

Page 34: A Quick Intro to ReactiveX

(function () { 'use strict'; var $input = $('#input'), $results = $('#results'); // this function returns a promise which is important function searchWikipedia(term) { // let's see what we are sending console.info(term); // use jquery to ajax some data to wikipedia return $.ajax({ url: 'http://en.wikipedia.org/w/api.php', dataType: 'jsonp', data: { action: 'opensearch', format: 'json', search: term } }).promise(); }

Page 35: A Quick Intro to ReactiveX

// Only get the value from each key up var keyups = Rx.Observable.fromEvent($input, 'keyup') .map(e => e.target.value) .filter(text => text.length > 3); // Now throttle/debounce the input for 500ms var throttled = keyups.throttle(500); // Now get only distinct values, so we eliminate others var distinct = throttled.distinctUntilChanged(); distinct .flatMapLatest(searchWikipedia) .subscribe( data => { var res = data[1]; // clear the markup $results.empty(); // emit an <li> with each result, $.each(res, (_, value) => $('<li>' + value + '</li>').appendTo($results)); }, error => { // clear the markup $results.empty(); $('<li>Error: ' + error + '</li>').appendTo($results); }); }());

Page 36: A Quick Intro to ReactiveX

Handy URLsReactiveX http://reactivex.io/

MSDN https://msdn.microsoft.com/en-us/data/gg577609

RxJS online bookhttps://xgrommx.github.io/rx-book/index.html

Netflixhttp://techblog.netflix.com/2013/01/reactive-programming-at-netflix.html

Rx Wikihttp://rxwiki.wikidot.com/101samples

Page 37: A Quick Intro to ReactiveX

Summary

Rx allows apps to easily work with asynchronous streaming data

Rx requires a bit of a cognitive leap

Resulting code is simpler and more logical