SlideShare a Scribd company logo
1 of 45
Download to read offline
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 (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# optimizedWoody Pewitt
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETAliaksandr Famin
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架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.0Yaser Zhian
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
 
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 LondonJiby 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) Datagreenwop
 
Functional programming in Swift
Functional programming in SwiftFunctional programming in Swift
Functional programming in SwiftJohn 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 BebopJSFestUA
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programmingScott Wlaschin
 

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

Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2
 

Recently uploaded (20)

Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in Uganda
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid Environments
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
 

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 !