SlideShare una empresa de Scribd logo
1 de 107
Descargar para leer sin conexión
@ladyleet
💜
Tracy Lee
See you in 2019!
https://2018.angular.tw/
@ladyleet
The Magic of
Reactive Programming:
With RxJS
Tracy Lee
Taiwan 2018
@ladyleet
@ladyleet
Reactive
Programming
@ladyleet
How many of you practice
Reactive Programming?
@ladyleet
Tracy Lee | @ladyleet
Co-Founder, This Dot Labs
● Google Developer Expert
● RxJS Core Team
● Community Rel, Node.js @ Node
Foundation
● JavaScript Developer - all the things
● Vue Vixens Board Member
● Google Women Techmakers Lead
● Modern Web Podcast
● Google Developer Group, Silicon Valley &
Triangle
@ladyleet
台灣的食物
太好吃了!!!
@ladyleet
如果有地方我應該去吃的話就
DM me on twitter @ladyleet!
@ladyleet
Back to important things
@ladyleet
Reactive
Programming
@ladyleet
So what is Reactive
Programming really?
@ladyleet
Wikipedia says…
Reactive programming is a programming
paradigm concerned with data streams and
the propagation of change.
@ladyleet
Wikipedia says…
This means that it becomes possible to
express static or dynamic data streams with
ease via the employed programming language
@ladyleet
Wikipedia says…
and that an inferred dependency within the
associated execution model exists, which
facilitates the automatic propagation of the
change involved with data flow.
@ladyleet
● Dealing with sets of events over time
● Automatic, implicit (not explicit),
propagation of change
● Each step doesn't know or care about the
previous step
● Each step performs an action when it
reacts to the incoming change
In Layman’s terms...
@ladyleet
In Layman’s terms...
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
TC39
● Promises
● Observables
WHATWG
● EventTarget Observable
Reactive programming in
standards
@ladyleet
● Added to browsers ~2014
● Added to Node.js ~2015
● ECMAScript 2015
● Push-based
● Single value
● Always async
● Eager
● Stateful
● Simple base API
● Simple transformation options (then, catch)
Promises
Promises
fetch('fruitsnacks.json')
.then(resp => resp.json())
.then(fruitsnacks => console.log('I have fruit snacks!'));
@ladyleet
● TC39 Proposal - Stage 1 https://github.com/tc39/proposal-observable
● RxJS is a reference implementation
● Simple base API
● Push-based
● Multiple values
● Sync or async
● Generally stateless
● Lazy
● Many transformation options OOTB (via RxJS)
Observable
Observable (RxJS)

import { ajax } from ‘rxjs/ajax’;
ajax.getJSON(‘fruitsnacks.json’)
.subscribe(fruitsnacks => console.log(fruitsnacks));
@ladyleet
● WHATWG Proposal - http://github.com/whatwg/dom/issues/544
● Add method called “on” to EventTarget
● Comes with operators (map, filter, first, TakeUntil)
EventTarget Observable
EventTarget Observable

button.on('click’);
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Reactive Programming in
Frameworks & Libraries
D3 VueAngular React
var numbers = [15, 8, 42, 4, 32];
function update() {
var selection = d3.select(“#chart”)
.selectAll(“.bar”).data(numbers)
.style(“height”, function(d) {
return d + “px”;
})
.style(“margin-top”, function(d) {
return (100 - d) + “px”;
});
Reactive Programming in D3
selection.enter()
.append(“div”).attr(“class”, “bar”)
.style(“height”, function(d) {
return (100 - d) + “px”;
})
.on(“click”, function(e, i) {
numbers.splice(i, 1);
update();
});
selection.exit().remove();
};
update();
@ladyleet
Reactive Programming in Angular
Angular & RxJS are besties
@ladyleet
Reactive Programming in Angular
NgRx
@ladyleet
● RxJS is a 1st class citizen
● .OnPush change detection strategy
● Angular Router
● Reactive forms
Reactive Programming in Angular
@ladyleet
Reactive Programming in React
redux-observableReact MobX
@ladyleet
Reactive Programming in React
redux-observableReact MobX
@ladyleet
Reactive Programming in React
redux-observableReact MobX
@ladyleet
Reactive Programming in React
React MobXredux-observable
@ladyleet
Reactive Programming in Vue
Vue-Rx
https://github.com/vuejs/vue-rx
@ladyleet
Reactive is just a fancy
term to quantify a way
of programming.
@ladyleet
Reactive Programming Patterns
appear where there is a natural fit for
events to be modeled as values over
time.
Web sockets, user events, animations,
HTTP requests, network connections,
file system changes, etc
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Everything can be modeled as an event
All applications are event driven
Everything can be represented as a set of values over time,
even events.
How do you think reactively?
@ladyleet
Everything can be
represented as a set of
values over time, even
events.
@ladyleet
Definition of set: a set in the math sense { a, b, c }.
Current mindset: When an action happens, you get one value
back.
New mindset: Treat events as sets of values.
Example sets: { }, { 0 }, { 1, 2, 3 }
Everything can be represented as a set
of values over time, even events.
@ladyleet
If everything is a set, you can do more with your data.
You can query them, map them, filter them…
Join and combine them in different ways…
Give something a half a set of things or things with a set of
parameters.
Everything can be represented as a set
of values over time, even events.
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
What is RxJS?
Domain specific language (DSL) for reacting to events
The most popular reactive programming library
@ladyleet
Did you know there are other dialects?
RxJava, RxPhp, Rx.NET, RxRuby, RxCPP, RxSwift...
@ladyleet
What an Observable Is
The simple, technical, nutshell version
Imagine it's just a function
function myObservable() {
}
We call it with an observer with handlers on it
function myObservable(observer) {
}
We call next on the observer to emit values
function myObservable(observer) {
observer.next(1);
}
We call error on the observer if there's a problem
function myObservable(observer) {
observer.next(1);
if (someCondition) {
observer.error(new Error('end of the world'));
}
}
We call complete on the observer if we're done emitting values
function myObservable(observer) {
observer.next(1);
if (someCondition) {
observer.error(new Error('end of the world'));
}
observer.complete();
}
To use our observable, we call it with an observer object
const observer = {
next(value) { console.log(value); },
error(err) { console.error(err); },
complete() { console.log('done'); },
};
myObservable(observer);
It could even return a teardown function to finalize
const teardown = myObservable({
next(value) { console.log(value); },
error(err) { console.error(err); },
complete() { console.log('done'); },
});
teardown();
@ladyleet
So why not just use functions?
We don't want those calls out of order
function myObservable(observer) {
observer.next(1);
if (someCondition) {
observer.error(new Error('end of the world'));
}
observer.complete();
observer.next('oops');
}
Was there a teardown returned or not?
const teardown = myObservable({
next(value) { console.log(value); },
error(err) { console.error(err); },
complete() { console.log('done'); },
});
if (teardown) teardown();
What if you don't want a handler?
myObservable({
next(value) { console.log(value); },
error(err) { console.error(err); },
});
complete? where are you?!
Tearing down on complete and error, too
const teardown = myObservable({
next(value) { console.log(value); },
error(err) { console.error(err); if (teardown) teardown(); },
complete() { console.log('done'); if (teardown) teardown(); },
});
if (teardown) teardown();
We can just take our function...
function myObservable(observer) {
observer.next(1);
if (someCondition) {
observer.error(new Error('end of the world'));
}
observer.complete();
}
… and wrap it in a class that handles that stuff
const myObservable = new Observable((observer) => {
observer.next(1);
if (someCondition) {
observer.error(new Error('end of the world'));
}
observer.complete();
});
Instead of calling it directly...
const teardown = myObservable({
next(value) { console.log(value); },
error(err) { console.error(err); if (teardown) teardown(); },
complete() { console.log('done'); if (teardown) teardown(); },
});
if (teardown) teardown();
...We call it via subscribe
const subscription = myObservable.subscribe({
next(value) { console.log(value); },
error(err) { console.error(err); },
complete() { console.log('done'); },
});
subscription.unsubscribe();
...We call it via subscribe
const subscription = myObservable.subscribe({
next(value) { console.log(value); },
error(err) { console.error(err); },
complete() { console.log('done'); },
});
subscription.unsubscribe();
@ladyleet
Observables Are Just Functions
With a lot of cool guarantees
@ladyleet
What is an "Operator"?
Just a transformation from one Observable into another
"operators" in Arrays
const arr = [1, 2, 3, 4, 5, 6, 7];
arr.filter(x => x % 2 === 0); // [2, 4, 6]
arr.map(x => x + x); // [2, 4, 6, 8, 10, 12, 14]
arr.filter(x => x % 2 === 0)
.map(x => x + x); // [4, 8, 12]
"operators" in Observables

import { of as observableOf } from 'rxjs';
import { map, filter } from 'rxjs/operators';
const src = observableOf(1, 2, 3, 4, 5, 6, 7);
src.pipe(
filter(x => x % 2 === 0),
map(x => x + x),
).subscribe(x => console.log(x)); // 4...8...12...
A simple map operator implementation

import { Observable } from 'rxjs';
export function map(fn) {
return (source) => new Observable(observer => {
return source.subscribe({
next(value) { observer.next(fn(value)); },
error(err) { observer.error(err); },
complete() { observer.complete(); },
});
});
}
Takes an observable and returns a new one

import { Observable } from 'rxjs';
export function map(fn) {
return (source) => new Observable(observer => {
return source.subscribe({
next(value) { observer.next(fn(value)); },
error(err) { observer.error(err); },
complete() { observer.complete(); },
});
});
}
Subscribes to the source...

import { Observable } from 'rxjs';
export function map(fn) {
return (source) => new Observable(observer => {
return source.subscribe({
next(value) { observer.next(fn(value)); },
error(err) { observer.error(err); },
complete() { observer.complete(); },
});
});
}
… and passes along the transformed value.

import { Observable } from 'rxjs';
export function map(fn) {
return (source) => new Observable(observer => {
return source.subscribe({
next(value) { observer.next(fn(value)); },
error(err) { observer.error(err); },
complete() { observer.complete(); },
});
});
}
… as well as sending along the other signals

import { Observable } from 'rxjs';
export function map(fn) {
return (source) => new Observable(observer => {
return source.subscribe({
next(value) { observer.next(fn(value)); },
error(err) { observer.error(err); },
complete() { observer.complete(); },
});
});
}
@ladyleet
There are 60+ operators in RxJS
(You probably won't need to implement your own often)
● map
● filter
● scan
● take
● reduce
● mergeMap
● concatMap
● switchMap
● takeUntil
● catchError
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we’ll talk about today
@ladyleet
With RxJS you can do cool things with
less code.
@ladyleet
Like drag and drop in Angular could be
easy.
@ladyleet
Show demo here
import { Component } from '@angular/core';
import { fromEvent } from 'rxjs/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';
import { filter, mergeMap, tap, takeUntil, map } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
mouseDown$ = fromEvent(document, 'mousedown');
mouseMove$ = fromEvent(document, 'mousemove');
mouseUp$ = fromEvent(document, 'mouseup');
subscription: Subscription;
targetMouseDown$ = this.mouseDown$.pipe(
filter((e: any) => e.target.matches('. '))
)
mouseDrag$ = this.targetMouseDown$.pipe(
mergeMap(({ target: draggable, offsetX: startX, offsetY: startY }) =>
this.mouseMove$.pipe(
tap((mouseMoveEvent: any) => {
mouseMoveEvent.preventDefault()
}),
map((mouseMoveEvent: any) => ({
left: mouseMoveEvent.clientX - startX,
top: mouseMoveEvent.clientY - startY,
draggable
})),
takeUntil(this.mouseUp$)
)
)
ngOnInit() {
this.subscription = new Subscription();
this.subscription.add(this.mouseDrag$.subscribe(({ top, left,
draggable }) => {
draggable.style.top = top + 'px';
draggable.style.left = left + 'px';
}));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
<div>
<img class="🍩 " src="./assets/donut.png" alt="donut">
<img class="🍟 " src="./assets/fries.png" alt="fries">
<img class="🐟 " src="./assets/goldfish.png" alt="goldfish">
<img class="🍔 " src="./assets/hamburger.png" alt="hamburger">
<img class="🍕 " src="./assets/pizza.png" alt="pizza">
<img class=" " src="./assets/taco.png" alt="taco">
<img class=" " src="./assets/hotdog.png" alt="hotdog">
</div>
@ladyleet
Show demo here
@ladyleet
It’s cute, right?
@ladyleet
We could do more complex things
like multiplexing over a websocket
using RxJS.
@ladyleet
Multiplexing over a websocket... what?
Sending and receiving multiple independent requests and
responses concurrently over the same websocket.
@ladyleet
import React from ‘react’;
import { StyleSheet, Text, View, Image, Button } from ‘react-native’;
import { webSocket } from ‘rxjs/webSocket’;
import { groupBy, mergeMap, takeUntil, finalize } from ‘rxjs/operators’;
import { timer } from ‘rxjs’;
import kenwheeler from ‘./ken_wheeler.png’;
export default class App extends React.Component {
state = { randomKens: {} };
socket$ = webSocket(‘ws://localhost:8080’);
requestKenHead() {
const msg = JSON.stringify({ type: ‘REQUEST_KEN_HEAD’ });
this.socket$.next(msg);
}
componentDidMount() {
const kenHead$ = this.socket$.pipe {
groupBy(data => data.id),
mergeMap(singleKenStream =>
singleKenStream.pipe(
takeUntil(
timer(3000),
),
finalize(() => {
const dataId = singleKenStream.key;
const randomKens = { ...this.state.randomKens };
delete randomKens[dataId];
this.setState({ randomKens });
})
)
const kenHead$ = this.socket$.pipe {
groupBy(data => data.id),
mergeMap(singleKenStream =>
singleKenStream.pipe(
takeUntil(
timer(3000),
),
finalize(() => {
const dataId = singleKenStream.key;
const randomKens = { ...this.state.randomKens };
delete randomKens[dataId];
this.setState({ randomKens });
})
)
)
);
this.subscription = kenHead$.subscribe(data => {
this.setState({
randomKens: {
...this.state.randomKens,
[data.id]: { id: data.id, x: data.x, y: data.y }
}
});
});
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
return (
<View>
{Object.values(this.state.randomKens).map(randomKen =>
<Image
key={randomKen.id}
source={kenwheeler}
style={{
position: ‘absolute’,
left: randomKen.x,
top: randomKen.y,
}}
/>
)}
<Button
onPress={() => this.requestKenHead()}
title=”add a ken bobble”
/>
</View>
);
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we talked about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we talked about today
@ladyleet
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
Things we talked about today
@ladyleet
Things we talked about today
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
@ladyleet
Things we talked about today
Reactive programming in standards
Reactive programming in frameworks & libraries
How to think reactively
What is RxJS?
How reactive programming makes development easier
@ladyleet
Click handlers
AJAX requests
Anything async
…or just call subscribe?
Easy ways to integrate RxJS
@ladyleet
RxJS docs - come contribute!
https://github.com/reactivex/rxjs
@ladyleet
Thank you!
Come hang with me on Twitter!
http://twitter.com/ladyleet
Grumpy cat game in Angular
https://github.com/ladyleet/grumpycat-rx-ng-neww
Bobble head Ken Wheeler react native app
https://github.com/ladyleet/ken-wheeler-react-native-multi-plex-web-socket
Node.js web socket server
https://github.com/ladyleet/ws-server

Más contenido relacionado

La actualidad más candente

20170624 GraphQL Presentation
20170624 GraphQL Presentation20170624 GraphQL Presentation
20170624 GraphQL PresentationMartin Heidegger
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark... Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...Databricks
 
Let's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptLet's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptMathieu Savy
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
No REST - Architecting Real-time Bulk Async APIs
No REST - Architecting Real-time Bulk Async APIsNo REST - Architecting Real-time Bulk Async APIs
No REST - Architecting Real-time Bulk Async APIsC4Media
 
【第一季第二期】Dive into javascript event
【第一季第二期】Dive into javascript event【第一季第二期】Dive into javascript event
【第一季第二期】Dive into javascript eventtbosstraining
 
FullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularFullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularLoiane Groner
 
React on Rails - RailsConf 2017 (Phoenix)
 React on Rails - RailsConf 2017 (Phoenix) React on Rails - RailsConf 2017 (Phoenix)
React on Rails - RailsConf 2017 (Phoenix)Jo Cranford
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with ReduxStephan Schmidt
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with ReduxMaurice De Beijer [MVP]
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisC4Media
 
Self-healing Applications with Ansible
Self-healing Applications with AnsibleSelf-healing Applications with Ansible
Self-healing Applications with AnsibleJürgen Etzlstorfer
 
The dev ops code has no servers
The dev ops code has no serversThe dev ops code has no servers
The dev ops code has no serversEd Anderson
 
Biz Talk Demo slideshare
Biz Talk Demo slideshareBiz Talk Demo slideshare
Biz Talk Demo slideshareerios
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and ReduxThom Nichols
 
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open WebKafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open WebHostedbyConfluent
 
Test or Go Fishing - A guide on how to write better Swift for iOS
Test or Go Fishing - A guide on how to write better Swift for iOSTest or Go Fishing - A guide on how to write better Swift for iOS
Test or Go Fishing - A guide on how to write better Swift for iOSPaul Ardeleanu
 

La actualidad más candente (20)

20170624 GraphQL Presentation
20170624 GraphQL Presentation20170624 GraphQL Presentation
20170624 GraphQL Presentation
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark... Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
 
Let's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptLet's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScript
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
No REST - Architecting Real-time Bulk Async APIs
No REST - Architecting Real-time Bulk Async APIsNo REST - Architecting Real-time Bulk Async APIs
No REST - Architecting Real-time Bulk Async APIs
 
【第一季第二期】Dive into javascript event
【第一季第二期】Dive into javascript event【第一季第二期】Dive into javascript event
【第一季第二期】Dive into javascript event
 
FullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularFullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + Angular
 
React on Rails - RailsConf 2017 (Phoenix)
 React on Rails - RailsConf 2017 (Phoenix) React on Rails - RailsConf 2017 (Phoenix)
React on Rails - RailsConf 2017 (Phoenix)
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with Redux
 
Think Async in Java 8
Think Async in Java 8Think Async in Java 8
Think Async in Java 8
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
 
Into the domain
Into the domainInto the domain
Into the domain
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Self-healing Applications with Ansible
Self-healing Applications with AnsibleSelf-healing Applications with Ansible
Self-healing Applications with Ansible
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
The dev ops code has no servers
The dev ops code has no serversThe dev ops code has no servers
The dev ops code has no servers
 
Biz Talk Demo slideshare
Biz Talk Demo slideshareBiz Talk Demo slideshare
Biz Talk Demo slideshare
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
 
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open WebKafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
 
Test or Go Fishing - A guide on how to write better Swift for iOS
Test or Go Fishing - A guide on how to write better Swift for iOSTest or Go Fishing - A guide on how to write better Swift for iOS
Test or Go Fishing - A guide on how to write better Swift for iOS
 

Similar a Reactive programming with RxJS - Taiwan

From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
Digital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and GoDigital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and GoC4Media
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...Codemotion
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.Techugo
 
Writing testable android apps
Writing testable android appsWriting testable android apps
Writing testable android appsK. Matthew Dupree
 
Human scaling on the front end
Human scaling on the front endHuman scaling on the front end
Human scaling on the front endRudy Rigot
 
Everything-as-code – Polyglotte Entwicklung in der Praxis
Everything-as-code – Polyglotte Entwicklung in der PraxisEverything-as-code – Polyglotte Entwicklung in der Praxis
Everything-as-code – Polyglotte Entwicklung in der PraxisQAware GmbH
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)Woonsan Ko
 
Social data visualization
Social data visualizationSocial data visualization
Social data visualizationCristina Serban
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbMongoDB APAC
 
5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)Christian Rokitta
 
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15GreeceJS
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsAlessandro Molina
 

Similar a Reactive programming with RxJS - Taiwan (20)

From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
Digital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and GoDigital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and Go
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.
 
Writing testable android apps
Writing testable android appsWriting testable android apps
Writing testable android apps
 
Testable android apps
Testable android appsTestable android apps
Testable android apps
 
Human scaling on the front end
Human scaling on the front endHuman scaling on the front end
Human scaling on the front end
 
Everything-as-code – Polyglotte Entwicklung in der Praxis
Everything-as-code – Polyglotte Entwicklung in der PraxisEverything-as-code – Polyglotte Entwicklung in der Praxis
Everything-as-code – Polyglotte Entwicklung in der Praxis
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
Social data visualization
Social data visualizationSocial data visualization
Social data visualization
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 
5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Reactive programming with RxJS - Taiwan

  • 2. Tracy Lee See you in 2019! https://2018.angular.tw/ @ladyleet
  • 3. The Magic of Reactive Programming: With RxJS Tracy Lee Taiwan 2018 @ladyleet
  • 5. @ladyleet How many of you practice Reactive Programming?
  • 6. @ladyleet Tracy Lee | @ladyleet Co-Founder, This Dot Labs ● Google Developer Expert ● RxJS Core Team ● Community Rel, Node.js @ Node Foundation ● JavaScript Developer - all the things ● Vue Vixens Board Member ● Google Women Techmakers Lead ● Modern Web Podcast ● Google Developer Group, Silicon Valley & Triangle
  • 11. @ladyleet So what is Reactive Programming really?
  • 12. @ladyleet Wikipedia says… Reactive programming is a programming paradigm concerned with data streams and the propagation of change.
  • 13. @ladyleet Wikipedia says… This means that it becomes possible to express static or dynamic data streams with ease via the employed programming language
  • 14. @ladyleet Wikipedia says… and that an inferred dependency within the associated execution model exists, which facilitates the automatic propagation of the change involved with data flow.
  • 15. @ladyleet ● Dealing with sets of events over time ● Automatic, implicit (not explicit), propagation of change ● Each step doesn't know or care about the previous step ● Each step performs an action when it reacts to the incoming change In Layman’s terms...
  • 17. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 18. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 19. @ladyleet TC39 ● Promises ● Observables WHATWG ● EventTarget Observable Reactive programming in standards
  • 20. @ladyleet ● Added to browsers ~2014 ● Added to Node.js ~2015 ● ECMAScript 2015 ● Push-based ● Single value ● Always async ● Eager ● Stateful ● Simple base API ● Simple transformation options (then, catch) Promises
  • 22. @ladyleet ● TC39 Proposal - Stage 1 https://github.com/tc39/proposal-observable ● RxJS is a reference implementation ● Simple base API ● Push-based ● Multiple values ● Sync or async ● Generally stateless ● Lazy ● Many transformation options OOTB (via RxJS) Observable
  • 23. Observable (RxJS) import { ajax } from ‘rxjs/ajax’; ajax.getJSON(‘fruitsnacks.json’) .subscribe(fruitsnacks => console.log(fruitsnacks));
  • 24. @ladyleet ● WHATWG Proposal - http://github.com/whatwg/dom/issues/544 ● Add method called “on” to EventTarget ● Comes with operators (map, filter, first, TakeUntil) EventTarget Observable
  • 26. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 27. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 28. @ladyleet Reactive Programming in Frameworks & Libraries D3 VueAngular React
  • 29. var numbers = [15, 8, 42, 4, 32]; function update() { var selection = d3.select(“#chart”) .selectAll(“.bar”).data(numbers) .style(“height”, function(d) { return d + “px”; }) .style(“margin-top”, function(d) { return (100 - d) + “px”; }); Reactive Programming in D3 selection.enter() .append(“div”).attr(“class”, “bar”) .style(“height”, function(d) { return (100 - d) + “px”; }) .on(“click”, function(e, i) { numbers.splice(i, 1); update(); }); selection.exit().remove(); }; update();
  • 30. @ladyleet Reactive Programming in Angular Angular & RxJS are besties
  • 32. @ladyleet ● RxJS is a 1st class citizen ● .OnPush change detection strategy ● Angular Router ● Reactive forms Reactive Programming in Angular
  • 33. @ladyleet Reactive Programming in React redux-observableReact MobX
  • 34. @ladyleet Reactive Programming in React redux-observableReact MobX
  • 35. @ladyleet Reactive Programming in React redux-observableReact MobX
  • 36. @ladyleet Reactive Programming in React React MobXredux-observable
  • 37. @ladyleet Reactive Programming in Vue Vue-Rx https://github.com/vuejs/vue-rx
  • 38. @ladyleet Reactive is just a fancy term to quantify a way of programming.
  • 39. @ladyleet Reactive Programming Patterns appear where there is a natural fit for events to be modeled as values over time. Web sockets, user events, animations, HTTP requests, network connections, file system changes, etc
  • 40. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 41. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 42. @ladyleet Everything can be modeled as an event All applications are event driven Everything can be represented as a set of values over time, even events. How do you think reactively?
  • 43. @ladyleet Everything can be represented as a set of values over time, even events.
  • 44. @ladyleet Definition of set: a set in the math sense { a, b, c }. Current mindset: When an action happens, you get one value back. New mindset: Treat events as sets of values. Example sets: { }, { 0 }, { 1, 2, 3 } Everything can be represented as a set of values over time, even events.
  • 45. @ladyleet If everything is a set, you can do more with your data. You can query them, map them, filter them… Join and combine them in different ways… Give something a half a set of things or things with a set of parameters. Everything can be represented as a set of values over time, even events.
  • 46. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 47. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 48. @ladyleet What is RxJS? Domain specific language (DSL) for reacting to events The most popular reactive programming library
  • 49. @ladyleet Did you know there are other dialects? RxJava, RxPhp, Rx.NET, RxRuby, RxCPP, RxSwift...
  • 50. @ladyleet What an Observable Is The simple, technical, nutshell version
  • 51. Imagine it's just a function function myObservable() { }
  • 52. We call it with an observer with handlers on it function myObservable(observer) { }
  • 53. We call next on the observer to emit values function myObservable(observer) { observer.next(1); }
  • 54. We call error on the observer if there's a problem function myObservable(observer) { observer.next(1); if (someCondition) { observer.error(new Error('end of the world')); } }
  • 55. We call complete on the observer if we're done emitting values function myObservable(observer) { observer.next(1); if (someCondition) { observer.error(new Error('end of the world')); } observer.complete(); }
  • 56. To use our observable, we call it with an observer object const observer = { next(value) { console.log(value); }, error(err) { console.error(err); }, complete() { console.log('done'); }, }; myObservable(observer);
  • 57. It could even return a teardown function to finalize const teardown = myObservable({ next(value) { console.log(value); }, error(err) { console.error(err); }, complete() { console.log('done'); }, }); teardown();
  • 58. @ladyleet So why not just use functions?
  • 59. We don't want those calls out of order function myObservable(observer) { observer.next(1); if (someCondition) { observer.error(new Error('end of the world')); } observer.complete(); observer.next('oops'); }
  • 60. Was there a teardown returned or not? const teardown = myObservable({ next(value) { console.log(value); }, error(err) { console.error(err); }, complete() { console.log('done'); }, }); if (teardown) teardown();
  • 61. What if you don't want a handler? myObservable({ next(value) { console.log(value); }, error(err) { console.error(err); }, }); complete? where are you?!
  • 62. Tearing down on complete and error, too const teardown = myObservable({ next(value) { console.log(value); }, error(err) { console.error(err); if (teardown) teardown(); }, complete() { console.log('done'); if (teardown) teardown(); }, }); if (teardown) teardown();
  • 63. We can just take our function... function myObservable(observer) { observer.next(1); if (someCondition) { observer.error(new Error('end of the world')); } observer.complete(); }
  • 64. … and wrap it in a class that handles that stuff const myObservable = new Observable((observer) => { observer.next(1); if (someCondition) { observer.error(new Error('end of the world')); } observer.complete(); });
  • 65. Instead of calling it directly... const teardown = myObservable({ next(value) { console.log(value); }, error(err) { console.error(err); if (teardown) teardown(); }, complete() { console.log('done'); if (teardown) teardown(); }, }); if (teardown) teardown();
  • 66. ...We call it via subscribe const subscription = myObservable.subscribe({ next(value) { console.log(value); }, error(err) { console.error(err); }, complete() { console.log('done'); }, }); subscription.unsubscribe();
  • 67. ...We call it via subscribe const subscription = myObservable.subscribe({ next(value) { console.log(value); }, error(err) { console.error(err); }, complete() { console.log('done'); }, }); subscription.unsubscribe();
  • 68. @ladyleet Observables Are Just Functions With a lot of cool guarantees
  • 69. @ladyleet What is an "Operator"? Just a transformation from one Observable into another
  • 70. "operators" in Arrays const arr = [1, 2, 3, 4, 5, 6, 7]; arr.filter(x => x % 2 === 0); // [2, 4, 6] arr.map(x => x + x); // [2, 4, 6, 8, 10, 12, 14] arr.filter(x => x % 2 === 0) .map(x => x + x); // [4, 8, 12]
  • 71. "operators" in Observables import { of as observableOf } from 'rxjs'; import { map, filter } from 'rxjs/operators'; const src = observableOf(1, 2, 3, 4, 5, 6, 7); src.pipe( filter(x => x % 2 === 0), map(x => x + x), ).subscribe(x => console.log(x)); // 4...8...12...
  • 72. A simple map operator implementation import { Observable } from 'rxjs'; export function map(fn) { return (source) => new Observable(observer => { return source.subscribe({ next(value) { observer.next(fn(value)); }, error(err) { observer.error(err); }, complete() { observer.complete(); }, }); }); }
  • 73. Takes an observable and returns a new one import { Observable } from 'rxjs'; export function map(fn) { return (source) => new Observable(observer => { return source.subscribe({ next(value) { observer.next(fn(value)); }, error(err) { observer.error(err); }, complete() { observer.complete(); }, }); }); }
  • 74. Subscribes to the source... import { Observable } from 'rxjs'; export function map(fn) { return (source) => new Observable(observer => { return source.subscribe({ next(value) { observer.next(fn(value)); }, error(err) { observer.error(err); }, complete() { observer.complete(); }, }); }); }
  • 75. … and passes along the transformed value. import { Observable } from 'rxjs'; export function map(fn) { return (source) => new Observable(observer => { return source.subscribe({ next(value) { observer.next(fn(value)); }, error(err) { observer.error(err); }, complete() { observer.complete(); }, }); }); }
  • 76. … as well as sending along the other signals import { Observable } from 'rxjs'; export function map(fn) { return (source) => new Observable(observer => { return source.subscribe({ next(value) { observer.next(fn(value)); }, error(err) { observer.error(err); }, complete() { observer.complete(); }, }); }); }
  • 77. @ladyleet There are 60+ operators in RxJS (You probably won't need to implement your own often) ● map ● filter ● scan ● take ● reduce ● mergeMap ● concatMap ● switchMap ● takeUntil ● catchError
  • 78. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 79. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we’ll talk about today
  • 80. @ladyleet With RxJS you can do cool things with less code.
  • 81. @ladyleet Like drag and drop in Angular could be easy.
  • 83. import { Component } from '@angular/core'; import { fromEvent } from 'rxjs/observable/fromEvent'; import { Subscription } from 'rxjs/Subscription'; import { filter, mergeMap, tap, takeUntil, map } from 'rxjs/operators';
  • 84. @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; mouseDown$ = fromEvent(document, 'mousedown'); mouseMove$ = fromEvent(document, 'mousemove'); mouseUp$ = fromEvent(document, 'mouseup'); subscription: Subscription;
  • 85. targetMouseDown$ = this.mouseDown$.pipe( filter((e: any) => e.target.matches('. ')) )
  • 86. mouseDrag$ = this.targetMouseDown$.pipe( mergeMap(({ target: draggable, offsetX: startX, offsetY: startY }) => this.mouseMove$.pipe( tap((mouseMoveEvent: any) => { mouseMoveEvent.preventDefault() }), map((mouseMoveEvent: any) => ({ left: mouseMoveEvent.clientX - startX, top: mouseMoveEvent.clientY - startY, draggable })), takeUntil(this.mouseUp$) ) )
  • 87. ngOnInit() { this.subscription = new Subscription(); this.subscription.add(this.mouseDrag$.subscribe(({ top, left, draggable }) => { draggable.style.top = top + 'px'; draggable.style.left = left + 'px'; })); } ngOnDestroy() { this.subscription.unsubscribe(); }
  • 88. <div> <img class="🍩 " src="./assets/donut.png" alt="donut"> <img class="🍟 " src="./assets/fries.png" alt="fries"> <img class="🐟 " src="./assets/goldfish.png" alt="goldfish"> <img class="🍔 " src="./assets/hamburger.png" alt="hamburger"> <img class="🍕 " src="./assets/pizza.png" alt="pizza"> <img class=" " src="./assets/taco.png" alt="taco"> <img class=" " src="./assets/hotdog.png" alt="hotdog"> </div>
  • 91. @ladyleet We could do more complex things like multiplexing over a websocket using RxJS.
  • 92. @ladyleet Multiplexing over a websocket... what? Sending and receiving multiple independent requests and responses concurrently over the same websocket.
  • 94. import React from ‘react’; import { StyleSheet, Text, View, Image, Button } from ‘react-native’; import { webSocket } from ‘rxjs/webSocket’; import { groupBy, mergeMap, takeUntil, finalize } from ‘rxjs/operators’; import { timer } from ‘rxjs’; import kenwheeler from ‘./ken_wheeler.png’;
  • 95. export default class App extends React.Component { state = { randomKens: {} }; socket$ = webSocket(‘ws://localhost:8080’); requestKenHead() { const msg = JSON.stringify({ type: ‘REQUEST_KEN_HEAD’ }); this.socket$.next(msg); }
  • 96. componentDidMount() { const kenHead$ = this.socket$.pipe { groupBy(data => data.id), mergeMap(singleKenStream => singleKenStream.pipe( takeUntil( timer(3000), ), finalize(() => { const dataId = singleKenStream.key; const randomKens = { ...this.state.randomKens }; delete randomKens[dataId]; this.setState({ randomKens }); }) )
  • 97. const kenHead$ = this.socket$.pipe { groupBy(data => data.id), mergeMap(singleKenStream => singleKenStream.pipe( takeUntil( timer(3000), ), finalize(() => { const dataId = singleKenStream.key; const randomKens = { ...this.state.randomKens }; delete randomKens[dataId]; this.setState({ randomKens }); }) ) ) );
  • 98. this.subscription = kenHead$.subscribe(data => { this.setState({ randomKens: { ...this.state.randomKens, [data.id]: { id: data.id, x: data.x, y: data.y } } }); }); componentWillUnmount() { this.subscription.unsubscribe(); }
  • 99. render() { return ( <View> {Object.values(this.state.randomKens).map(randomKen => <Image key={randomKen.id} source={kenwheeler} style={{ position: ‘absolute’, left: randomKen.x, top: randomKen.y, }} /> )} <Button onPress={() => this.requestKenHead()} title=”add a ken bobble” /> </View> );
  • 100. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we talked about today
  • 101. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we talked about today
  • 102. @ladyleet Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier Things we talked about today
  • 103. @ladyleet Things we talked about today Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier
  • 104. @ladyleet Things we talked about today Reactive programming in standards Reactive programming in frameworks & libraries How to think reactively What is RxJS? How reactive programming makes development easier
  • 105. @ladyleet Click handlers AJAX requests Anything async …or just call subscribe? Easy ways to integrate RxJS
  • 106. @ladyleet RxJS docs - come contribute! https://github.com/reactivex/rxjs
  • 107. @ladyleet Thank you! Come hang with me on Twitter! http://twitter.com/ladyleet Grumpy cat game in Angular https://github.com/ladyleet/grumpycat-rx-ng-neww Bobble head Ken Wheeler react native app https://github.com/ladyleet/ken-wheeler-react-native-multi-plex-web-socket Node.js web socket server https://github.com/ladyleet/ws-server