SlideShare a Scribd company logo
@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

More Related Content

What's hot (20)

PDF
20170624 GraphQL Presentation
Martin Heidegger
 
PDF
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Databricks
 
PDF
Let's discover React and Redux with TypeScript
Mathieu Savy
 
PPTX
React + Redux + TypeScript === ♥
Remo Jansen
 
PDF
No REST - Architecting Real-time Bulk Async APIs
C4Media
 
KEY
【第一季第二期】Dive into javascript event
tbosstraining
 
PDF
FullStack Reativo com Spring WebFlux + Angular
Loiane Groner
 
PDF
React on Rails - RailsConf 2017 (Phoenix)
Jo Cranford
 
PDF
State Models for React with Redux
Stephan Schmidt
 
PPTX
Think Async in Java 8
Dmitry Alexandrov
 
PPTX
Better React state management with Redux
Maurice De Beijer [MVP]
 
ODP
Into the domain
Knoldus Inc.
 
PDF
Beyond Breakpoints: A Tour of Dynamic Analysis
C4Media
 
PPTX
Self-healing Applications with Ansible
Jürgen Etzlstorfer
 
PDF
JavaScript Promises
Derek Willian Stavis
 
PPTX
The dev ops code has no servers
Ed Anderson
 
PPT
Biz Talk Demo slideshare
erios
 
PPTX
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
PDF
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
HostedbyConfluent
 
PDF
Test or Go Fishing - A guide on how to write better Swift for iOS
Paul Ardeleanu
 
20170624 GraphQL Presentation
Martin Heidegger
 
Validating Big Data Jobs—Stopping Failures Before Production on Apache Spark...
Databricks
 
Let's discover React and Redux with TypeScript
Mathieu Savy
 
React + Redux + TypeScript === ♥
Remo Jansen
 
No REST - Architecting Real-time Bulk Async APIs
C4Media
 
【第一季第二期】Dive into javascript event
tbosstraining
 
FullStack Reativo com Spring WebFlux + Angular
Loiane Groner
 
React on Rails - RailsConf 2017 (Phoenix)
Jo Cranford
 
State Models for React with Redux
Stephan Schmidt
 
Think Async in Java 8
Dmitry Alexandrov
 
Better React state management with Redux
Maurice De Beijer [MVP]
 
Into the domain
Knoldus Inc.
 
Beyond Breakpoints: A Tour of Dynamic Analysis
C4Media
 
Self-healing Applications with Ansible
Jürgen Etzlstorfer
 
JavaScript Promises
Derek Willian Stavis
 
The dev ops code has no servers
Ed Anderson
 
Biz Talk Demo slideshare
erios
 
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
Kafka and GraphQL: Misconceptions and Connections | Gerard Klijs, Open Web
HostedbyConfluent
 
Test or Go Fishing - A guide on how to write better Swift for iOS
Paul Ardeleanu
 

Similar to Reactive programming with RxJS - Taiwan (20)

PDF
Reactive programming and RxJS
Ravi Mone
 
PPTX
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Codemotion
 
PPTX
Functional reactive programming
Ahmed Kamel Taha
 
PPTX
Luis Atencio on RxJS
Luis Atencio
 
PDF
My Gentle Introduction to RxJS
Mattia Occhiuto
 
PPTX
Functional Reactive Programming with RxJS
stefanmayer13
 
PDF
Functional Reactive Programming in JavaScript
zupzup.org
 
PDF
Moving towards Reactive Programming
Deepak Shevani
 
PDF
Demystifying Reactive Programming
Tom Bulatewicz, PhD
 
PPTX
Reactive programming with rx java
CongTrung Vnit
 
PPTX
Solve it Differently with Reactive Programming
Supun Dissanayake
 
PDF
RxJS - The Reactive Extensions for JavaScript
Viliam Elischer
 
PPTX
Reactive programming
saykopatt
 
ODP
Appstate
Tomas Kulich
 
PDF
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
PDF
[DevDay 2019] Reactive Programming with JavaScript - By Pham Nguyen Duc, Web ...
DevDay Da Nang
 
PDF
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
PDF
Reactive Programming
Zhentian Wan
 
PDF
Reactive x
Gabriel Araujo
 
Reactive programming and RxJS
Ravi Mone
 
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Codemotion
 
Functional reactive programming
Ahmed Kamel Taha
 
Luis Atencio on RxJS
Luis Atencio
 
My Gentle Introduction to RxJS
Mattia Occhiuto
 
Functional Reactive Programming with RxJS
stefanmayer13
 
Functional Reactive Programming in JavaScript
zupzup.org
 
Moving towards Reactive Programming
Deepak Shevani
 
Demystifying Reactive Programming
Tom Bulatewicz, PhD
 
Reactive programming with rx java
CongTrung Vnit
 
Solve it Differently with Reactive Programming
Supun Dissanayake
 
RxJS - The Reactive Extensions for JavaScript
Viliam Elischer
 
Reactive programming
saykopatt
 
Appstate
Tomas Kulich
 
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
[DevDay 2019] Reactive Programming with JavaScript - By Pham Nguyen Duc, Web ...
DevDay Da Nang
 
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
Reactive Programming
Zhentian Wan
 
Reactive x
Gabriel Araujo
 
Ad

Recently uploaded (20)

PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Kubernetes - Architecture & Components.pdf
geethak285
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Ad

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