SlideShare a Scribd company logo
Observables + React!
hello.
Ian Irvine
@IanIrvine
ian@meridianapps.com
Meridian = apps for places
Retailers, stadiums, airports,
hospitals, etc.
CARRIER 8:30 AM 100%
CARRIER 8:30 AM 100%
CARRIER 8:30 AM 100%
Transportation
CARRIER 8:30 AM 100%
Retail
Hospitals
Hotels
Campus
CARRIER 8:30 AM 100%
Agenda
Who cares about Observables!
Wait, first, what’s an Observable!
How they’ve helped me out in React!
How they might one day help you out in React
Fair Warning
Why should I care about Observables (you jerk)
Why should I learn yet another async paradigm when obviously
${_.sample([Promises, Tasks, streams, generators, async/await,
CSP, Futures, Fibers, just use callbacks dammit])} are better…
They’re coming to React (maybe)
https://github.com/facebook/react/issues/3398
They’re coming to Javascript (maybe)
https://www.youtube.com/watch?v=DqMFX91ToLw
They’re coming to Angular 2! (maybe)
http://victorsavkin.com/post/110170125256/change-detection-in-angular-2
One more sloth slide
Events
document.addEventListener(
"mousemove",
(e) => console.log(e)
);
!
emitter.on('thing', (e) => console.log(e));
model.on('change:attr', (e) => console.log(e));
Events
var isDown = false, state;
!
function mousedown(e) {
isDown = true;
state = {
startX: e.offsetX,
startY: e.offsetY
};
}
!
function mousemove(e) {
if (!isDown) { return; }
var delta = {
endX: e.clientX - state.startX,
endY: e.clientY - state.startY
};
!
//code goes here
}
!
function mouseup(e) {
isDown = false;
state = null;
}
function dispose() {
elem.removeEventListener('mousedown', mousedown, false);
elem.removeEventListener('mouseup', mouseup, false);
doc.removeEventListener('mousemove', mousemove, false);
}
!
elem.addEventListener('mousedown', mousedown, false);
elem.addEventListener('mouseup', mouseup, false);
doc.addEventListener('mousemove', mousemove, false);
Iterators
interface Iterable<T> {
iterator(): Iterator<T>;
}
!
interface Iterator<T> {
hasNext(): Boolean;
next(): T;
}
var things = getIterator();
!
while (things.hasNext()) {
console.log(things.next());
}
!
// or
!
for (let next of things) {
console.log(next);
}
> { value: ‘thing1’ done:false }
> { value: ‘thing2’ done:false }
> { value: ‘thing3’ done:true }
So what’s an Observable
It’s the Iterable<T> to event streams.
interface Observable<T> {
subscribe(observer: Observer<T>): Disposable;
}
!
interface Observer<T> {
onNext(value: T): void;
onError(exception: any): void;
onCompleted(): void;
}
Observables from Iterables
interface Enumerable<T> {
[Symbol.iterator](): Enumerator<T>;
}
!
interface Enumerator<T> {
next(): EnumeratorValue<T>;
}
!
interface EnumeratorValue<T> {
done: Boolean;
value: T;
}
interface Observable<T> {
subscribe(observer: Observer<T>): Disposable;
}
!
interface Observer<T> {
onNext(value: T): void;
onError(exception: any): void;
onCompleted(): void;
}
interface Observable<T> {
subscribe(observer: Observer<T>): Disposable;
}
!
interface Observer<T> {
onNext(value: T): void;
onError(exception: any): void;
onCompleted(): void;
}
Observables from Iterables
interface Enumerable<T> {
[Symbol.iterator](): Enumerator<T>;
}
!
interface Enumerator<T> {
next(): EnumeratorValue<T>;
}
!
interface EnumeratorValue<T> {
done: Boolean;
value: T;
}
interface Observable<T> {
subscribe(observer: Observer<T>): Disposable;
}
!
interface Observer<T> {
onNext(value: T): void;
onError(exception: any): void;
onCompleted(): void;
}
Observables from Iterables
interface Enumerable<T> {
[Symbol.iterator](): Enumerator<T>;
}
!
interface Enumerator<T> {
next(): EnumeratorValue<T>;
}
!
interface EnumeratorValue<T> {
done: Boolean;
value: T;
}
interface Enumerable<T> {
[Symbol.iterator](): Enumerator<T>;
}
!
interface Enumerator<T> {
next(): EnumeratorValue<T>;
}
!
interface EnumeratorValue<T> {
done: Boolean;
value: T;
}
interface Observable<T> {
subscribe(observer: Observer<T>): Disposable;
}
!
interface Observer<T> {
onNext(value: T): void;
onError(exception: any): void;
onCompleted(): void;
}
Observables from Iterables
Observables are like Iterables stretched out across time
[“A”, “B”, “C”, “D”, “E”] //…etc
A B C D E
So what’s RX
RX is a particular set of rules for Observables
onNext
Zero or more values
onError
This thing that was sending
me things is done sending
me things, forever
onComplete
So what’s RX
Plus a boatload of operators
WhoCares.gif
Remember when you found out you could replace this style
of code:
let ret = [];
let xs = [1,2,3,4,5,6];
for (let i = 0; i < xs.length; i++) {
let val = xs[i];
if (!(val % 2)) {
ret.push(val);
}
}
with:
let ret = [1,2,3,4,5,6].filter((val) => !(val % 2));
?
RX + Observables turns Events into Collections
Examples
let elementDrags = (el) => {
return dom.mouseDown(el)
.map((event) => {
return dom.mousemove(document)
.takeUntil(dom.mouseup(el));
}).concatAll();
};
!
elementDrags(image)
.forEach(moveImage)
Examples
function searchWikipedia(term) {
return fetch(`http://en.wikipedia.org/w/api.php?action=opensearch&term=${term}`);
}
!
let keyup = Rx.Observable.fromEvent(document.querySelector('input'), 'keyup')
.map((e) => e.target.value)
.filter((text) => text.length > 2)
.debounce(750)
.distinctUntilChanged();
!
// don't send new requests for keyups that don't change the value, like arrow keys
!
let subscription = keyup.flatMapLatest(searchWikipedia)
.subscribe((data) => {
// bind data to DOM
});
!
// when we're finished
!
subscription.dispose();
How can we use these with React
Short answer: I don’t really know yet
• Pass streams around as props!
• Use them to manage real time event streams
(websockets etc)!
• Use them to model data flows in Flux!
• Use them to model state changes in components!
• Animations?
!
Historically, our apps have derived a user’s current location
through piece of network infrastructure called a Real Time
Location System (RTLS)
APs work in coordination with the RTLS to
calculate position based on RSSI
triangulation.
The Problem
The Problem
==>
The Solution
We can solve this with a simple transformation between the
two maps…
But to create this transformation we need at least two
reference points in both coordinate systems.
import {Observable} from 'rx';
!
export default function(id, floor, controlPointStream) {
const timer = Observable.interval(7000);
!
function url(controlPoints) {
return `${SERVER}/api/device?id=${id}&foor=${floor}&ref_points=${controlPoints}`;
}
!
function getDevices(controlPoints) {
return fetch(url(controlPoints));
}
!
return controlPointStream.flapMapLatest((controlPoints) => {
return timer.startWith(-1)
.flatMap(getDevices(controlPoints));
});
}
import React from 'react';
import rx from 'rx';
!
export default React.createClass({
componentWillMount() {
this.subject = new rx.BehaviorSubject(this.props.initialRefPoints);
this.stream = this.subject.asObservable();
},
!
componentDidUpdate(prevProps) {
if (prevProps.rtlsRefPointString !== this.props.rtlsRefPointString) {
this.subject.onNext(this.props.rtlsRefPointString);
}
},
!
render() {
return (
<div>
<MeridianCoordinatePicker stream={this.stream} {...this.props} />
<RTLSCoordinatePicker stream={this.stream} {...this.props} />
</div>
);
}
});
import React from 'react';
import rx from 'rx';
import Entity from './Entity';
import makeDeviceStream from './makeDeviceStream';
!
export default React.createClass({
getInitialState() {
return {devices: null, referencePoints: [0,0]}
},
!
componentWillMount() {
this.subscription = makeDeviceStream(
this.props.id, this.props.floor, this.props.stream)
.map((devices) => {
return Entity.from(devices);
})
.subscribe((devices) => this.setState({devices}));
},
!
componentWillUnmount() {
this.subscription.dispose();
},
!
render() {
return (
<CoordinateSurface
devices={this.state.devices}
referencePoints={this.state.referencePoints}
{...this.props} />
);
}
})
Demos!
React “side-loaded” data
class MyComponent extends React.Component {
observe() {
return {
updates: rx.DOM.fromWebsocket(this.props.url)
.map((event) => JSON.parse(event.data))
};
}
!
render() {
return (
<div>
Last Update: this.data.updates
</div>
);
}
}
Things I haven’t tried yet
Modeling component state as Observable stream
class SearchWikipedia extends RxReact.Component {
constructor(props) {
super(props);
this.keyup = FuncSubject.create();
}
getStateStream() {
return (
this.keyup
.map((e) => e.target.value)
.filter(text => text.length > 2)
.throttle(750)
.distinctUntilChanged()
.flatMapLatest(text => searchWikipedia(text))
.filter(data => data.length >= 2)
.map(results => ({results: results[1]}))
);
}
render() {
var results = this.state && this.state.results || [];
return (
<div>
<div>Start Typing</div>
<input type="text" id="searchtext" onKeyUp={this.keyup}/>
<ul id="results">{
results.map((result, index) =>
<li key={index}>{result}</li>
)
}</ul>
</div>
);
}
}
https://github.com/fdecampredon/rx-react
Things I haven’t tried yet
Combining Observables with Flux
• https://github.com/fdecampredon/rx-flux!
• http://r3dm.github.io/thundercats/!
• https://github.com/cell303/flurx
Things I didn’t have time for
• Backpressure in Observables
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/backpressure.md
• Hot vs Cold Observables
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables
• Schedulers
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/schedulers.md
Sources
• Intro To Reactive Programming you’ve been missing
(https://gist.github.com/staltz/868e7e9bc2a7b8c1f754)!
• Coursera’s Reactive Programming Course (starts this
week!)!
• reactivex.io!
• @ReactiveX
We’re hiring!!
!
http://www.meridianapps.com/about#jobs
!
ian@meridianapps.com
For more information: 
Ian Irvine
ian@meridianapps.com
!

More Related Content

What's hot

JavaScript ES10 and React Js Introduction
JavaScript ES10 and React Js IntroductionJavaScript ES10 and React Js Introduction
JavaScript ES10 and React Js Introduction
Amanpreet Singh
 
Stack
StackStack
Zio from Home
Zio from Home Zio from Home
Zio from Home
Wiem Zine Elabidine
 
05 queues
05 queues05 queues
05 queues
Rajan Gautam
 
Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3
Synapseindiappsdevelopment
 
Chap03alg
Chap03algChap03alg
Chap03alg
Munkhchimeg
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
Wiem Zine Elabidine
 
Qprgs
QprgsQprgs
Os3 2
Os3 2Os3 2
Os3 2
issbp
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
Nithin Kumar,VVCE, Mysuru
 
Gophercon 2016 Communicating Sequential Goroutines
Gophercon 2016 Communicating Sequential GoroutinesGophercon 2016 Communicating Sequential Goroutines
Gophercon 2016 Communicating Sequential Goroutines
Adrian Cockcroft
 

What's hot (11)

JavaScript ES10 and React Js Introduction
JavaScript ES10 and React Js IntroductionJavaScript ES10 and React Js Introduction
JavaScript ES10 and React Js Introduction
 
Stack
StackStack
Stack
 
Zio from Home
Zio from Home Zio from Home
Zio from Home
 
05 queues
05 queues05 queues
05 queues
 
Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3
 
Chap03alg
Chap03algChap03alg
Chap03alg
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
 
Qprgs
QprgsQprgs
Qprgs
 
Os3 2
Os3 2Os3 2
Os3 2
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
Gophercon 2016 Communicating Sequential Goroutines
Gophercon 2016 Communicating Sequential GoroutinesGophercon 2016 Communicating Sequential Goroutines
Gophercon 2016 Communicating Sequential Goroutines
 

Similar to pdx-react-observables

Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
The Reactive Landscape
The Reactive LandscapeThe Reactive Landscape
The Reactive Landscape
Red Hat Developers
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
Christoffer Noring
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
jeffz
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
AvitoTech
 
Monitoring for the masses
Monitoring for the massesMonitoring for the masses
Monitoring for the masses
Rodrigo Fernandez
 
Rx: Curing Your Asynchronous Programming Blues | QCon London
Rx: Curing Your Asynchronous Programming Blues |  QCon LondonRx: Curing Your Asynchronous Programming Blues |  QCon London
Rx: Curing Your Asynchronous Programming Blues | QCon London
Jiby John
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
The STL
The STLThe STL
The STL
adil raja
 
Functional programming in Swift
Functional programming in SwiftFunctional programming in Swift
Functional programming in Swift
John Pham
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless Bebop
JSFestUA
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
Ignacio Martín
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
Scott Wlaschin
 
Ch03
Ch03Ch03
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
Christoffer Noring
 

Similar to pdx-react-observables (20)

Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
The Reactive Landscape
The Reactive LandscapeThe Reactive Landscape
The Reactive Landscape
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
 
Monitoring for the masses
Monitoring for the massesMonitoring for the masses
Monitoring for the masses
 
Rx: Curing Your Asynchronous Programming Blues | QCon London
Rx: Curing Your Asynchronous Programming Blues |  QCon LondonRx: Curing Your Asynchronous Programming Blues |  QCon London
Rx: Curing Your Asynchronous Programming Blues | QCon London
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
The STL
The STLThe STL
The STL
 
Functional programming in Swift
Functional programming in SwiftFunctional programming in Swift
Functional programming in Swift
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless Bebop
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
Ch03
Ch03Ch03
Ch03
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 

Recently uploaded

一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLESINTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
anfaltahir1010
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 

Recently uploaded (20)

一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLESINTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 

pdx-react-observables

  • 3. Meridian = apps for places Retailers, stadiums, airports, hospitals, etc. CARRIER 8:30 AM 100% CARRIER 8:30 AM 100% CARRIER 8:30 AM 100% Transportation CARRIER 8:30 AM 100% Retail Hospitals Hotels Campus CARRIER 8:30 AM 100%
  • 4.
  • 5.
  • 6. Agenda Who cares about Observables! Wait, first, what’s an Observable! How they’ve helped me out in React! How they might one day help you out in React
  • 8. Why should I care about Observables (you jerk) Why should I learn yet another async paradigm when obviously ${_.sample([Promises, Tasks, streams, generators, async/await, CSP, Futures, Fibers, just use callbacks dammit])} are better…
  • 9.
  • 10. They’re coming to React (maybe) https://github.com/facebook/react/issues/3398
  • 11. They’re coming to Javascript (maybe) https://www.youtube.com/watch?v=DqMFX91ToLw
  • 12. They’re coming to Angular 2! (maybe) http://victorsavkin.com/post/110170125256/change-detection-in-angular-2
  • 13. One more sloth slide
  • 14. Events document.addEventListener( "mousemove", (e) => console.log(e) ); ! emitter.on('thing', (e) => console.log(e)); model.on('change:attr', (e) => console.log(e));
  • 15. Events var isDown = false, state; ! function mousedown(e) { isDown = true; state = { startX: e.offsetX, startY: e.offsetY }; } ! function mousemove(e) { if (!isDown) { return; } var delta = { endX: e.clientX - state.startX, endY: e.clientY - state.startY }; ! //code goes here } ! function mouseup(e) { isDown = false; state = null; } function dispose() { elem.removeEventListener('mousedown', mousedown, false); elem.removeEventListener('mouseup', mouseup, false); doc.removeEventListener('mousemove', mousemove, false); } ! elem.addEventListener('mousedown', mousedown, false); elem.addEventListener('mouseup', mouseup, false); doc.addEventListener('mousemove', mousemove, false);
  • 16. Iterators interface Iterable<T> { iterator(): Iterator<T>; } ! interface Iterator<T> { hasNext(): Boolean; next(): T; } var things = getIterator(); ! while (things.hasNext()) { console.log(things.next()); } ! // or ! for (let next of things) { console.log(next); } > { value: ‘thing1’ done:false } > { value: ‘thing2’ done:false } > { value: ‘thing3’ done:true }
  • 17. So what’s an Observable It’s the Iterable<T> to event streams. interface Observable<T> { subscribe(observer: Observer<T>): Disposable; } ! interface Observer<T> { onNext(value: T): void; onError(exception: any): void; onCompleted(): void; }
  • 18. Observables from Iterables interface Enumerable<T> { [Symbol.iterator](): Enumerator<T>; } ! interface Enumerator<T> { next(): EnumeratorValue<T>; } ! interface EnumeratorValue<T> { done: Boolean; value: T; } interface Observable<T> { subscribe(observer: Observer<T>): Disposable; } ! interface Observer<T> { onNext(value: T): void; onError(exception: any): void; onCompleted(): void; }
  • 19. interface Observable<T> { subscribe(observer: Observer<T>): Disposable; } ! interface Observer<T> { onNext(value: T): void; onError(exception: any): void; onCompleted(): void; } Observables from Iterables interface Enumerable<T> { [Symbol.iterator](): Enumerator<T>; } ! interface Enumerator<T> { next(): EnumeratorValue<T>; } ! interface EnumeratorValue<T> { done: Boolean; value: T; }
  • 20. interface Observable<T> { subscribe(observer: Observer<T>): Disposable; } ! interface Observer<T> { onNext(value: T): void; onError(exception: any): void; onCompleted(): void; } Observables from Iterables interface Enumerable<T> { [Symbol.iterator](): Enumerator<T>; } ! interface Enumerator<T> { next(): EnumeratorValue<T>; } ! interface EnumeratorValue<T> { done: Boolean; value: T; }
  • 21. interface Enumerable<T> { [Symbol.iterator](): Enumerator<T>; } ! interface Enumerator<T> { next(): EnumeratorValue<T>; } ! interface EnumeratorValue<T> { done: Boolean; value: T; } interface Observable<T> { subscribe(observer: Observer<T>): Disposable; } ! interface Observer<T> { onNext(value: T): void; onError(exception: any): void; onCompleted(): void; } Observables from Iterables
  • 22. Observables are like Iterables stretched out across time [“A”, “B”, “C”, “D”, “E”] //…etc A B C D E
  • 23. So what’s RX RX is a particular set of rules for Observables onNext Zero or more values onError This thing that was sending me things is done sending me things, forever onComplete
  • 24. So what’s RX Plus a boatload of operators
  • 25. WhoCares.gif Remember when you found out you could replace this style of code: let ret = []; let xs = [1,2,3,4,5,6]; for (let i = 0; i < xs.length; i++) { let val = xs[i]; if (!(val % 2)) { ret.push(val); } } with: let ret = [1,2,3,4,5,6].filter((val) => !(val % 2)); ?
  • 26. RX + Observables turns Events into Collections
  • 27. Examples let elementDrags = (el) => { return dom.mouseDown(el) .map((event) => { return dom.mousemove(document) .takeUntil(dom.mouseup(el)); }).concatAll(); }; ! elementDrags(image) .forEach(moveImage)
  • 28. Examples function searchWikipedia(term) { return fetch(`http://en.wikipedia.org/w/api.php?action=opensearch&term=${term}`); } ! let keyup = Rx.Observable.fromEvent(document.querySelector('input'), 'keyup') .map((e) => e.target.value) .filter((text) => text.length > 2) .debounce(750) .distinctUntilChanged(); ! // don't send new requests for keyups that don't change the value, like arrow keys ! let subscription = keyup.flatMapLatest(searchWikipedia) .subscribe((data) => { // bind data to DOM }); ! // when we're finished ! subscription.dispose();
  • 29. How can we use these with React Short answer: I don’t really know yet • Pass streams around as props! • Use them to manage real time event streams (websockets etc)! • Use them to model data flows in Flux! • Use them to model state changes in components! • Animations?
  • 30. ! Historically, our apps have derived a user’s current location through piece of network infrastructure called a Real Time Location System (RTLS) APs work in coordination with the RTLS to calculate position based on RSSI triangulation. The Problem
  • 32. The Solution We can solve this with a simple transformation between the two maps… But to create this transformation we need at least two reference points in both coordinate systems.
  • 33.
  • 34.
  • 35. import {Observable} from 'rx'; ! export default function(id, floor, controlPointStream) { const timer = Observable.interval(7000); ! function url(controlPoints) { return `${SERVER}/api/device?id=${id}&foor=${floor}&ref_points=${controlPoints}`; } ! function getDevices(controlPoints) { return fetch(url(controlPoints)); } ! return controlPointStream.flapMapLatest((controlPoints) => { return timer.startWith(-1) .flatMap(getDevices(controlPoints)); }); }
  • 36. import React from 'react'; import rx from 'rx'; ! export default React.createClass({ componentWillMount() { this.subject = new rx.BehaviorSubject(this.props.initialRefPoints); this.stream = this.subject.asObservable(); }, ! componentDidUpdate(prevProps) { if (prevProps.rtlsRefPointString !== this.props.rtlsRefPointString) { this.subject.onNext(this.props.rtlsRefPointString); } }, ! render() { return ( <div> <MeridianCoordinatePicker stream={this.stream} {...this.props} /> <RTLSCoordinatePicker stream={this.stream} {...this.props} /> </div> ); } });
  • 37. import React from 'react'; import rx from 'rx'; import Entity from './Entity'; import makeDeviceStream from './makeDeviceStream'; ! export default React.createClass({ getInitialState() { return {devices: null, referencePoints: [0,0]} }, ! componentWillMount() { this.subscription = makeDeviceStream( this.props.id, this.props.floor, this.props.stream) .map((devices) => { return Entity.from(devices); }) .subscribe((devices) => this.setState({devices})); }, ! componentWillUnmount() { this.subscription.dispose(); }, ! render() { return ( <CoordinateSurface devices={this.state.devices} referencePoints={this.state.referencePoints} {...this.props} /> ); } })
  • 39. React “side-loaded” data class MyComponent extends React.Component { observe() { return { updates: rx.DOM.fromWebsocket(this.props.url) .map((event) => JSON.parse(event.data)) }; } ! render() { return ( <div> Last Update: this.data.updates </div> ); } }
  • 40. Things I haven’t tried yet Modeling component state as Observable stream class SearchWikipedia extends RxReact.Component { constructor(props) { super(props); this.keyup = FuncSubject.create(); } getStateStream() { return ( this.keyup .map((e) => e.target.value) .filter(text => text.length > 2) .throttle(750) .distinctUntilChanged() .flatMapLatest(text => searchWikipedia(text)) .filter(data => data.length >= 2) .map(results => ({results: results[1]})) ); } render() { var results = this.state && this.state.results || []; return ( <div> <div>Start Typing</div> <input type="text" id="searchtext" onKeyUp={this.keyup}/> <ul id="results">{ results.map((result, index) => <li key={index}>{result}</li> ) }</ul> </div> ); } } https://github.com/fdecampredon/rx-react
  • 41. Things I haven’t tried yet Combining Observables with Flux • https://github.com/fdecampredon/rx-flux! • http://r3dm.github.io/thundercats/! • https://github.com/cell303/flurx
  • 42. Things I didn’t have time for • Backpressure in Observables https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/backpressure.md • Hot vs Cold Observables https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables • Schedulers https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/schedulers.md
  • 43. Sources • Intro To Reactive Programming you’ve been missing (https://gist.github.com/staltz/868e7e9bc2a7b8c1f754)! • Coursera’s Reactive Programming Course (starts this week!)! • reactivex.io! • @ReactiveX
  • 45. For more information: Ian Irvine ian@meridianapps.com !