A Quick Intro to Rx
Troy Miles 28 April 2016
Slides + Code
http://www.slideshare.net/rockncoder/a-quick-intro-to-
reactivex
https://github.com/Rockncoder/rx-demos
Agenda
Quick introduction
What are the Reactive Extensions (Rx)?
Why should I care?
How do I get started?
Summary
Troy Miles
Troy Miles aka the
RocknCoder
Over 36 years of
programming experience
Speaker and author
Author of jQuery Essentials
rockncoder@gmail.com
@therockncoder
Upcoming talks
Angular 2 Weekend Workshop - Los Angeles

May 14th & 15th
Build a game in 60 minutes - Irvine

May 24th
SoCal Code Camp - San Diego

June 25th & 26th
Cross Platform Game Programming - Irvine

July 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
Observable
The thing to watch
Functions called operators
Create
Filter
Aggregate
Perform
Handle errors
many more
Operators ‘o plenty
Aggregate
All
Amb
and_
And
Any
apply
as_blocking
AsObservable
AssertEqual
asyncAction
asyncFunc
Average
averageDouble
averageFloat
averageInteger
averageLong
blocking
Buffer
bufferWithCount
bufferWithTime
bufferWithTimeOrCou
nt
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 NuGet
Rx-Main: The main package, often all you need
Includes
Rx-Core
Rx-Linq
Rx-Interfaces
Rx-PlatformServices
Other packages
Rx-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
static	IEnumerable<string>	EndlessBarrageOfEmail()	
				{	
								var	random	=	new	Random();	
								var	emails	=	new	List<String>	{	"Here	is	an	email!",		
"Another	email!",	"Yet	another	email!"	};	
								while(true)	
								{	
												//	Return	some	random	emails	at	random	intervals.	
												yield	return	emails[random.Next(emails.Count)];	
												Thread.Sleep(random.Next(1000));	
								}	
				}
static	void	Main()	
				{	
								var	myInbox	=	EndlessBarrageOfEmail().ToObservable();	
								//	Instead	of	making	you	wait	5	minutes,	we	will	just	check	every	three	seconds	
instead.	:)	
								var	getMailEveryThreeSeconds	=	myInbox.Buffer(TimeSpan.FromSeconds(3));	//		Was	
.BufferWithTime(...	
								getMailEveryThreeSeconds.Subscribe(emails	=>	
								{	
												Console.WriteLine("You've	got	{0}	new	messages!		Here	they	are!",	
emails.Count());	
												foreach	(var	email	in	emails)	
												{	
																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 URLs
ReactiveX

http://reactivex.io/
MSDN 

https://msdn.microsoft.com/en-us/data/gg577609
RxJS online book

https://xgrommx.github.io/rx-book/index.html
Netflix

http://techblog.netflix.com/2013/01/reactive-programming-at-netflix.html
Rx Wiki

http://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

A Quick Intro to ReactiveX