Upload
troy-miles
View
264
Download
5
Embed Size (px)
Citation preview
A Quick Intro to RxTroy Miles 28 April 2016
Slides + Code
http://www.slideshare.net/rockncoder/a-quick-intro-to-reactivex
https://github.com/Rockncoder/rx-demos
AgendaQuick introduction
What are the Reactive Extensions (Rx)?
Why should I care?
How do I get started?
Summary
Troy MilesTroy Miles aka the RocknCoder
Over 36 years of programming experience
Speaker and author
Author of jQuery Essentials
@therockncoder
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
What are the Reactive Extensions?
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
Rx = Observables + LINQ + Schedulers
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
Observer
The observer pattern
Functions
onNext
onError
onCompleted
ObservableThe thing to watch
Functions called operators
Create
Filter
Aggregate
Perform
Handle errors
many more
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
Subscription
Ties the observer and observable together
Function
Subscribe
Dispose
Promise v Observable
Promise Observable
async helper yes yes
values single multiple
errors single multiple
cancellable no yes
retry no yes
Why should I care?
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?
Who uses this stuff?
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
Is it in my language?
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
How do I get started?
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
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
Rx.NET (C#)
Install Rx via NuGetRx-Main: The main package, often all you need
Includes
Rx-Core
Rx-Linq
Rx-Interfaces
Rx-PlatformServices
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
staticIEnumerable<string>EndlessBarrageOfEmail(){varrandom=newRandom();varemails=newList<String>{"Hereisanemail!",
"Anotheremail!","Yetanotheremail!"};
while(true){//Returnsomerandomemailsatrandomintervals.yieldreturnemails[random.Next(emails.Count)];Thread.Sleep(random.Next(1000));}}
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();}
RxJS (JavaScript)
Uses Wikipedia’s search service
Normally written using callbacks or promises
Written using ES2015, so it looks a bit weird
(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(); }
// 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); }); }());
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
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