SlideShare una empresa de Scribd logo
1 de 69
Descargar para leer sin conexión
Rxjs
everything is a stream
Christoffer Noring
Google Developer Expert
@chris_noring
Why Rxjs?
We want to deal with async in a “synchronous looking way”
We want something better than promises
We want one paradigm for async to rule them all
nce upon a time in async land
There were callbacks
Callbacks turned into callback hell
Promises to the rescue
service
.getData()
.then(getMoreData)
.then(getEvenMore)
.then(andSomeMore)
Looks great right?
But promises were flawed
No cancellation
eal with other async concepts like mouse positions, clicks, use
No rich composition
And brexit happened
Cumbersome to retry
Only returns one value
Observables to the rescue
What is an observable
Observable is just a function
that takes an observer and returns a function
Observer: an object with next, error, complete methods
Rx.Observable.create((observer) => {
observer.next(1);
observer.error(‘error’);
observer.complete();
})
1 2 3 4 5 6 7
stream of value over time
Promise
vs Array
vs Observable
list
.map( x = > x.prop )
.filter( x => x > 2 )
.take( 2 )
Array
list
.map( x = > x.prop )
.filter( x => x > 2 )
.take( 2 )
.subscribe(
x => console.log(x),
err => console.log(err) )
Observable
Promise
service.get()
.then( x => console.log(x) )
.catch( err => console.log(err) ) but can also
- Cancelled
- Retried
Array like,
handles async
Manual creation of an
Observable
var stream$ = Rx.Observable.create((observer) =>{
})})
Emits
stream
.subscribe(
(data) => { console.log( data ); }
)
1
next()
observer.next(1);
2
next()
observer.next(2);
3
next()
observer.next(3);
let stream$ = Rx.Observable.create((observer) =>{
})
stream$
.subscribe(
(data) => { console.log( data ); }
(err) => { console.log(err); }
)
Emits 1
next()
observer.next(1);
error message
error()
observer.error(‘something went wrong’)
let stream = Rx.Observable.create((observer) =>{
})})
stream
.subscribe(
(data) => { console.log( data ); }
(err) => { console.log(err) },
() => { console.log(‘completed’) }
)
Emits 1
next()
observer.next(1);
complete()
observer.complete();
Subscribe to an Observable
let subscription =
stream$.subscribe(
fnValue,,
fnError,,
fnCompleted
)
Cancelling
.unsubscribe()
let subscription = Rx.Observable.interval(1000)
.subscribe((data) => console.log(data))
subscription.unsubscribe();
Define a dispose function1
2
var homemadeStream = Rx.Observable.create((observer) => {
var i=0;
});
var subscription2 = homemadeStream.subscribe((val) => {
console.log('Homemade val',val);
});
setTimeout(() => {
console.log('Cancelling homemadeStream');
subscription2.unsubscribe();
}, 1500); Calling dispose
Produce values
till someone calls unsubscribe
var handle = setInterval(() => {
observer.next( i++ );
}, 500);
Define whats to happen
on unsubscribe
return function(){
console.log('Disposing timeout');
clearTimeout( handle );
}
You will always create
an observable from something
Rx.Observable.fromArray([ 1,2,3,4 ])
Rx.Observable.fromEvent(element, ‘event’);
Rx.Observable.fromArray(eventEmitter, ‘data’, function(){})
Rx.Observable.fromNodeCallback(fs.createFile)
Rx.Observable.fromCallback(obj.callback)
Rx.Observable.fromPromise(promise)
Rx.Observable.fromIterable(function *() { yield 20 })
Rx.Observable.range(1,3)
Rx.Observable.interval(miliseconds)
Wrap an observable
next()
error()
complete()
var stream = Rx.Observable.create((observer) => {
var request = new XMLHttpRequest();
request.open( ‘GET’, ‘url’ );
request.onload =() =>{
if(request.status === 200) {
} else {
}
}
request.onerror = () => { }
request.send();
})
stream.subscribe(
)
observer.next( request.response );
(result) => { console.log( result ); }
Get our data
observer.complete();
() => { console.log(‘completed’); }
No more data, close stream
observer.error( new Error( request.statusText ) )
(err) => { console.log(err) },
observer.error( new Error(‘unknown error’) );
Error
Error
Hot vs Cold Observable
Cold Observable
recorded tv show
Hot observable
Live streaming
eg World Cup Final
Observables are cold by default,
unless you make them hot
0 1 2 3 4
3 4
publisher$.connect();let publisher$ = Rx.Observable
.interval(1000)
.take(5)
.publish();
publisher$.subscribe(
data => console.log('subscriber from first minute',data),
err => console.log(err),
() => console.log('completed')
)
setTimeout(() => {
publisher$.subscribe(
data => console.log('subscriber from 2nd minute', data),
err => console.log(err),
() => console.log('completed')
)
}, 3000)
1
2
Warm Observables
waiting for someone to subscribe
let obs = Rx.Observable.interval(1000).take(3).publish().refCount();
setTimeout(() => {
obs.subscribe(data => console.log('sub1', data));
},1000)
setTimeout(() => {
obs.subscribe(data => console.log('sub2', data));
},2000)
Values begin emitting here
Receives values based on
where producer
is at, i.e hot
Share operator
flips between hot and col
let stream$ = Rx.Observable.create((observer) => {
observer.next( 1 );
observer.next( 2 );
observer.next( 3 );
observer.complete();
}).share()
1) Becomes a Hot Observable
An Observable has not completed when a
new subscription comes and subscribers > 0
2) Reverts to Cold Observable
Number of subscribers becomes 0 before a new subscription takes place. I.e a sce
No subscribers left
Not done yet
3) Reverts to Cold Observable
when an Observable completed before a new subscription
Already done
Hot vs Cold Summary
Hot shares values between subscribers AND
ubscriber receives values depending on where the Producer is cu
HOT
COLD
Everyone has their own producer of values
publish() + connect()
You can create an observable
from almost any async concept
Operators however gives it
its power
Remember:
But:
Operators
makes your code look like linq
120+ operators Rxjs 4
60+ Rxjs 5
Combination
Conditional
Multicasting
Filtering
Transformation
Utility
Categories
in production
Marble diagram
how does that operator work
Operator
Most operators are covered at rxmarbles.com
Stream 1 2 3
Other stream 4 5
Resulting stream 1 2 3 4 5
Operator example
var stream = Rx.Observable.of(1,2,3,4,5);
stream
stream.subscribe((data) => { console.log(‘data’); })
Operators :
map()
filter()
3
Emits
6
.map((val) => {
return val + 1;
})
changes the value
.filter((val) => {
return val % 3 === 0;
})
filters out values
Do
var stream = Rx.Observable.of(1,2,3,4,5);
var subscription = stream
.filter(function(val){
return val % 2 === 0;
});
subscription.subscribe(function(val){
console.log('Val',val);
})
Echos every value
without changing it,
used for logging
.do((val) => {
console.log('Current val', val);
})
Current val 1
Current val 2
Current val 3
Current val 4
Current val 5
Subscribe:
2
4
sample
var debounceTime = Rx.Observable
.fromEvent(button,'click')
debounceTime.subscribe( function(){
console.log('mouse pressed');
})
waits x ms and
returns latest emitted
Ignores all generated
mouse click events
for 2 seconds.sampleTime(2000);
Clicking save button
2secclick click click click click
save()
switchMap
Switch map,
complete something based on a condition
breakCondition = Rx.Observable.fromEvent(document,'click');
breakCondition.switchMap((val) => {
return Rx.Observable.interval(3000).mapTo(‘Do this');
})
breakCondition.subscribe((val) => {
console.log('Switch map', val);
})
Intended action is completed/restarted
by ‘breakCondition’
etc..
Do this
Do this
Do this
Do this
Do this
click
click
source.subscribe((data) => {
console.log( data );
})
flatMap
let source = Rx.DOM.getJSON( 'data2.json' )
return Rx.Observable.fromArray( data ).map((row) => {
return row.props.name;
});
return observable
.flatMap((data) => {
} );
We get an array response that we want to emit row by row
We use flatMap instead of map because :
We want to flatten our list to one stream
flatMap explained
when you create a list of observables flatMap flattens that list s
Great when changing from one type of stream to another
Without it you would have to listen to every single substream, w
eve
nt
eve
nt
eve
nt
eve
nt
ajax ajax ajax ajax
json json json json
flatMap
map
Problem : Autocomplete
Listen for keyboard presses
Filter so we only do server trip after x number of
chars are entered
Do ajax call based on filtered input
Cash responses,
don’t do unnecessary calls to http server
The procedural approach
let input = $(‘#input’);
input.bind(‘keyup’,() = >{
let val = input.val()
if(val.length >= 3 ) {
if( isCached( val ) ) { buildList( getFromCache(val) ); return; }
doAjax( val ).then( (response) => {
buildList( response.json() )
storeInCache( val, response.json() )
});
}
})
fetch if x characters long
return if cached
do ajax
Ok solution but NOT so fluent
We need 3 methods to deal with cache
The observable approach
Stream modeling
key key key key key key
FILTER
AJAX CALL
jso
n
jso
n
MAP
key key key key key key key
respons
e
respons
e
flatmapExample = Rx.Observable.fromEvent(input,'keyup')
flatmapExample.subscribe(
(result) =>{ console.log('Flatmap', result); buildList( result ) }
)
more fluent
Transform event to char.map((ev) => {
return ev.target.value;
})
Wait until we have 3 chars
.filter(function(text){
return text.length >=3;
})
Only perform search if this ‘search’ is unique.distinctUntilChanged()
Excellent to use when
coming from
one stream to another
.switchMap((val) => {
return Rx.DOM.getJSON( 'data3.json' );
})
Error handling
when streams fail
error
completion
.catch() completion
completion
no values
completion
values, WIN!
.catch()
merge
.catch()
merge
onErrorResumeNext
completion
values, WIN
error
completion
no values
retry
let stream = Rx.Observable.interval(1000)
.take(6);
.map((n) => {
if(n === 2) {
throw 'ex';
}
return n;
})
Produce error
.retry(2)
Number of tries
before hitting error callback
stream.subscribe(
(data) => console.log(data)
(error) => console.log(error)
1
Emits
3
Makes x attempts before error cb is called
retryWhen
delay between attempts
let stream = Rx.Observable.interval(1000)
.take(6);
delay, 200 ms.retryWhen((errors) => {
return errors.delay(200);
})
.map((n) => {
if(n === 2) {
throw 'ex';
}
return n;
})
produce an error when
= 2
stream.subscribe(
(data) => console.log(data)
(error) => console.log(error) for those shaky connections
What did we learn so far?
We can cancel with .unsubsribe()
We can retry easily
A stream generates a continuous stream of values
Operators manipulate either the values or the stream/s
We can “patch” an erronous stream with a .catch()
or
Ignore a failing stream altogether
with onErrorResumeNext
Schedulers
bending time
What about schedulers and
testing?
Because scheduler has its own virtual clock
Anything scheduled on that scheduler
will adhere to time denoted on the clock
I.e we can bend time for ex unit testing
Marble testing
Yes it has to do with marbles,
essentially its visual comparison
QUnit.test("Test simple emit 1 2 3", function(assert){
// setup
const lhsMarble = '-x-y-z';
const expected = '-x-y-z';
const expectedMap = {
x: 1,
y: 2,
z : 3
};
const lhs$ = testScheduler.createHotObservable(lhsMarble, expectedMap);
const myAlgorithm = ( lhs ) =>
Rx.Observable
.from( lhs );
const actual$ = myAlgorithm( lhs$ );
//assert
testScheduler.expectObservable(actual$).toBe(expected, expectedMap);
testScheduler.flush();
});
Create a hot observable from
a marble pattern
QUnit.test("Test filter", function(assert){
const lhsMarble = '-x-y-z';
const expected = '---y-';
const expectedMap = {
x: 1,
y: 2,
z : 3
};
const lhs$ = testScheduler.createHotObservable(lhsMarble,expectedMap);
const myAlgorithm = ( lhs ) =>
Rx.Observable
.from( lhs )
.filter(x => x % 2 === 0 );
const actual$ = myAlgorithm( lhs$ );
//assert
testScheduler.expectObservable(actual$).toBe(expected, expectedMap);
testScheduler.flush();
});
An extra hyphen,
to make time match
Yes -
means something
Its a time increment
There are other characters
besides - like
# = error and | = completion
QUnit.test("Test error", function(assert){
const lhsMarble = '-#';
const expected = '#';
const expectedMap = {
};
//const lhs$ = testScheduler.createHotObservable(lhsMarble, expectedMap);
const myAlgorithm = ( lhs ) =>
Rx.Observable
.from( lhs );
const actual$ = myAlgorithm( Rx.Observable.throw('error') );
//assert
testScheduler.expectObservable(actual$).toBe(expected, expectedMap);
testScheduler.flush();
})
Will cause an error
Error will happen
Test Summary
You use a descriptive marble to define behaviour
-x-y-z
There are symbols that mean something like :
-
#
|
Comparing promises
to Rxjs
.then vs .subscribe
getData()
.then(
)
getData().subscribe(
)
I will keep on streaming values
(data) => console.log(data),
(data) => console.log(data),
(err) => console.log(err) (err) => console.log(err)
user
order
orderItem
Fetch user
Then fetch order
Lastly fetch order item
Cascading calls
Response:
//getUser
stream
.subscribe((orderItem) => {
console.log('OrderItem',orderItem.id);
})
{ id: 11, userId : 1 }.then(getOrderByUser)
.switchMap((user) => {
//getOrder
return Rx.Observable.of({ id : 11, userId : user.id }).delay(3000)
})
{ id: 123, orderId : 11 }.then(getOrderItemByOrder)
.switchMap((order) => {
//getOrderItem
return Rx.Observable.of({ id: 114, orderId: order.id })
})
{ id: 1 }getUser()
var stream = Rx.Observable.of({ id : 1 });
So we can see the
first user observable
being dropped when
user 2 is emitted
Short word on switchMap
is to ensure we throw away the other calls when a new user is em
We don’t want
getUser
getOrderByUser
getOrderItemByOrder
to complete if a new user is emitted
1 2 3
2 4 5
Not continued
Replaces above
stream
user
orders messages
Fetch user
Fetch in parallell
Cascading call
wait for the first
.subscribe(
(data) => {
console.log( 'orders', data[0] );
console.log( 'messages', data[0] );
}
)
var stream = Rx.Observable.of([{ id : 1 }, { id : 2 }]);
getUser()
We wait for user
function getOrdersAndMessages(user){
return Promise.all([
getOrdersByUser( user.id ),
getMessagesByUser( user.id )
])
}
.then(getOrdersAndMessages)
stream.switchMap((user) => {
return Rx.Observable.forkJoin(
Rx.Observable.of([ { id: 1, userId : user.id } ]).delay(500), // orders
Rx.Observable.of([ { id: 100, userId : user.id } ]).delay(1500) //messages
)
})
Calls to orders and message
can happen in parallel
Orders,Messages
arrive at the same time
Last summary
We can use schedulers to easily test our code
Cascading calls can easily be setup
switchMap over flatMap when doing ajax calls
because we need it to abandon the stream if
the first condition change
Further Reading
angular.io/resources Rxjs Ultimate
https://github.com/ReactiveX/rxjs
Free book
Official docs
Thank you

Más contenido relacionado

La actualidad más candente

Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Astrails
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots DeepAnshu Sharma
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot Nidhi Chauhan
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7Mike North
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Advanced Akka For Architects
Advanced Akka For ArchitectsAdvanced Akka For Architects
Advanced Akka For ArchitectsLightbend
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringCary Millsap
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterReact table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterKaty Slemon
 
Durable functions
Durable functionsDurable functions
Durable functions명신 김
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of ControlChad Hietala
 

La actualidad más candente (20)

Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Angular mix chrisnoring
Angular mix chrisnoringAngular mix chrisnoring
Angular mix chrisnoring
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Advanced Akka For Architects
Advanced Akka For ArchitectsAdvanced Akka For Architects
Advanced Akka For Architects
 
Why realm?
Why realm?Why realm?
Why realm?
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and Monitoring
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-es
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterReact table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilter
 
Durable functions
Durable functionsDurable functions
Durable functions
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
 

Similar a Rxjs marble-testing

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...GeeksLab Odessa
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Oscar Renalias
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkNikos Kalogridis
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)GreeceJS
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Marble Testing RxJS streams
Marble Testing RxJS streamsMarble Testing RxJS streams
Marble Testing RxJS streamsIlia Idakiev
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSAbul Hasan
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJSRavi Mone
 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014hezamu
 
From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptMaurice De Beijer [MVP]
 

Similar a Rxjs marble-testing (20)

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI framework
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Marble Testing RxJS streams
Marble Testing RxJS streamsMarble Testing RxJS streams
Marble Testing RxJS streams
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJS
 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014
 
From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java script
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 

Más de Christoffer Noring (19)

Azure signalR
Azure signalRAzure signalR
Azure signalR
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
Game dev 101 part 2
Game dev 101   part 2Game dev 101   part 2
Game dev 101 part 2
 
Game dev workshop
Game dev workshopGame dev workshop
Game dev workshop
 
Deploying your static web app to the Cloud
Deploying your static web app to the CloudDeploying your static web app to the Cloud
Deploying your static web app to the Cloud
 
IaaS with ARM templates for Azure
IaaS with ARM templates for AzureIaaS with ARM templates for Azure
IaaS with ARM templates for Azure
 
Learning Svelte
Learning SvelteLearning Svelte
Learning Svelte
 
Ng spain
Ng spainNg spain
Ng spain
 
Angular Schematics
Angular SchematicsAngular Schematics
Angular Schematics
 
Design thinking
Design thinkingDesign thinking
Design thinking
 
Keynote ijs
Keynote ijsKeynote ijs
Keynote ijs
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
 
Kendoui
KendouiKendoui
Kendoui
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Finjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster strongerFinjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster stronger
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Nativescript with angular 2
Nativescript with angular 2Nativescript with angular 2
Nativescript with angular 2
 

Último

Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
Top 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTop 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTopCSSGallery
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarEMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarThousandEyes
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxNeo4j
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024Brian Pichman
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4DianaGray10
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3DianaGray10
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Muhammad Tiham Siddiqui
 

Último (20)

Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
Top 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTop 10 Squarespace Development Companies
Top 10 Squarespace Development Companies
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarEMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? Webinar
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)
 

Rxjs marble-testing

  • 1. Rxjs everything is a stream Christoffer Noring Google Developer Expert @chris_noring
  • 2. Why Rxjs? We want to deal with async in a “synchronous looking way” We want something better than promises We want one paradigm for async to rule them all
  • 3. nce upon a time in async land There were callbacks Callbacks turned into callback hell
  • 4. Promises to the rescue service .getData() .then(getMoreData) .then(getEvenMore) .then(andSomeMore) Looks great right?
  • 5. But promises were flawed No cancellation eal with other async concepts like mouse positions, clicks, use No rich composition And brexit happened Cumbersome to retry Only returns one value
  • 7. What is an observable Observable is just a function that takes an observer and returns a function Observer: an object with next, error, complete methods Rx.Observable.create((observer) => { observer.next(1); observer.error(‘error’); observer.complete(); }) 1 2 3 4 5 6 7 stream of value over time
  • 8. Promise vs Array vs Observable list .map( x = > x.prop ) .filter( x => x > 2 ) .take( 2 ) Array list .map( x = > x.prop ) .filter( x => x > 2 ) .take( 2 ) .subscribe( x => console.log(x), err => console.log(err) ) Observable Promise service.get() .then( x => console.log(x) ) .catch( err => console.log(err) ) but can also - Cancelled - Retried Array like, handles async
  • 9. Manual creation of an Observable
  • 10. var stream$ = Rx.Observable.create((observer) =>{ })}) Emits stream .subscribe( (data) => { console.log( data ); } ) 1 next() observer.next(1); 2 next() observer.next(2); 3 next() observer.next(3);
  • 11. let stream$ = Rx.Observable.create((observer) =>{ }) stream$ .subscribe( (data) => { console.log( data ); } (err) => { console.log(err); } ) Emits 1 next() observer.next(1); error message error() observer.error(‘something went wrong’)
  • 12. let stream = Rx.Observable.create((observer) =>{ })}) stream .subscribe( (data) => { console.log( data ); } (err) => { console.log(err) }, () => { console.log(‘completed’) } ) Emits 1 next() observer.next(1); complete() observer.complete();
  • 13. Subscribe to an Observable
  • 15. Cancelling .unsubscribe() let subscription = Rx.Observable.interval(1000) .subscribe((data) => console.log(data)) subscription.unsubscribe(); Define a dispose function1 2
  • 16. var homemadeStream = Rx.Observable.create((observer) => { var i=0; }); var subscription2 = homemadeStream.subscribe((val) => { console.log('Homemade val',val); }); setTimeout(() => { console.log('Cancelling homemadeStream'); subscription2.unsubscribe(); }, 1500); Calling dispose Produce values till someone calls unsubscribe var handle = setInterval(() => { observer.next( i++ ); }, 500); Define whats to happen on unsubscribe return function(){ console.log('Disposing timeout'); clearTimeout( handle ); }
  • 17. You will always create an observable from something
  • 18. Rx.Observable.fromArray([ 1,2,3,4 ]) Rx.Observable.fromEvent(element, ‘event’); Rx.Observable.fromArray(eventEmitter, ‘data’, function(){}) Rx.Observable.fromNodeCallback(fs.createFile) Rx.Observable.fromCallback(obj.callback) Rx.Observable.fromPromise(promise) Rx.Observable.fromIterable(function *() { yield 20 }) Rx.Observable.range(1,3) Rx.Observable.interval(miliseconds)
  • 20. var stream = Rx.Observable.create((observer) => { var request = new XMLHttpRequest(); request.open( ‘GET’, ‘url’ ); request.onload =() =>{ if(request.status === 200) { } else { } } request.onerror = () => { } request.send(); }) stream.subscribe( ) observer.next( request.response ); (result) => { console.log( result ); } Get our data observer.complete(); () => { console.log(‘completed’); } No more data, close stream observer.error( new Error( request.statusText ) ) (err) => { console.log(err) }, observer.error( new Error(‘unknown error’) ); Error Error
  • 21. Hot vs Cold Observable
  • 22. Cold Observable recorded tv show Hot observable Live streaming eg World Cup Final
  • 23. Observables are cold by default, unless you make them hot 0 1 2 3 4 3 4 publisher$.connect();let publisher$ = Rx.Observable .interval(1000) .take(5) .publish(); publisher$.subscribe( data => console.log('subscriber from first minute',data), err => console.log(err), () => console.log('completed') ) setTimeout(() => { publisher$.subscribe( data => console.log('subscriber from 2nd minute', data), err => console.log(err), () => console.log('completed') ) }, 3000) 1 2
  • 24. Warm Observables waiting for someone to subscribe let obs = Rx.Observable.interval(1000).take(3).publish().refCount(); setTimeout(() => { obs.subscribe(data => console.log('sub1', data)); },1000) setTimeout(() => { obs.subscribe(data => console.log('sub2', data)); },2000) Values begin emitting here Receives values based on where producer is at, i.e hot
  • 25. Share operator flips between hot and col let stream$ = Rx.Observable.create((observer) => { observer.next( 1 ); observer.next( 2 ); observer.next( 3 ); observer.complete(); }).share()
  • 26. 1) Becomes a Hot Observable An Observable has not completed when a new subscription comes and subscribers > 0 2) Reverts to Cold Observable Number of subscribers becomes 0 before a new subscription takes place. I.e a sce No subscribers left Not done yet 3) Reverts to Cold Observable when an Observable completed before a new subscription Already done
  • 27. Hot vs Cold Summary Hot shares values between subscribers AND ubscriber receives values depending on where the Producer is cu HOT COLD Everyone has their own producer of values publish() + connect()
  • 28. You can create an observable from almost any async concept Operators however gives it its power Remember: But:
  • 29. Operators makes your code look like linq
  • 30. 120+ operators Rxjs 4 60+ Rxjs 5 Combination Conditional Multicasting Filtering Transformation Utility Categories in production
  • 31. Marble diagram how does that operator work
  • 32. Operator Most operators are covered at rxmarbles.com Stream 1 2 3 Other stream 4 5 Resulting stream 1 2 3 4 5
  • 33. Operator example var stream = Rx.Observable.of(1,2,3,4,5); stream stream.subscribe((data) => { console.log(‘data’); }) Operators : map() filter() 3 Emits 6 .map((val) => { return val + 1; }) changes the value .filter((val) => { return val % 3 === 0; }) filters out values
  • 34. Do var stream = Rx.Observable.of(1,2,3,4,5); var subscription = stream .filter(function(val){ return val % 2 === 0; }); subscription.subscribe(function(val){ console.log('Val',val); }) Echos every value without changing it, used for logging .do((val) => { console.log('Current val', val); }) Current val 1 Current val 2 Current val 3 Current val 4 Current val 5 Subscribe: 2 4
  • 35. sample var debounceTime = Rx.Observable .fromEvent(button,'click') debounceTime.subscribe( function(){ console.log('mouse pressed'); }) waits x ms and returns latest emitted Ignores all generated mouse click events for 2 seconds.sampleTime(2000); Clicking save button 2secclick click click click click save()
  • 36. switchMap Switch map, complete something based on a condition breakCondition = Rx.Observable.fromEvent(document,'click'); breakCondition.switchMap((val) => { return Rx.Observable.interval(3000).mapTo(‘Do this'); }) breakCondition.subscribe((val) => { console.log('Switch map', val); }) Intended action is completed/restarted by ‘breakCondition’ etc.. Do this Do this Do this Do this Do this click click
  • 37. source.subscribe((data) => { console.log( data ); }) flatMap let source = Rx.DOM.getJSON( 'data2.json' ) return Rx.Observable.fromArray( data ).map((row) => { return row.props.name; }); return observable .flatMap((data) => { } ); We get an array response that we want to emit row by row We use flatMap instead of map because : We want to flatten our list to one stream
  • 38. flatMap explained when you create a list of observables flatMap flattens that list s Great when changing from one type of stream to another Without it you would have to listen to every single substream, w eve nt eve nt eve nt eve nt ajax ajax ajax ajax json json json json flatMap map
  • 39. Problem : Autocomplete Listen for keyboard presses Filter so we only do server trip after x number of chars are entered Do ajax call based on filtered input Cash responses, don’t do unnecessary calls to http server
  • 41. let input = $(‘#input’); input.bind(‘keyup’,() = >{ let val = input.val() if(val.length >= 3 ) { if( isCached( val ) ) { buildList( getFromCache(val) ); return; } doAjax( val ).then( (response) => { buildList( response.json() ) storeInCache( val, response.json() ) }); } }) fetch if x characters long return if cached do ajax Ok solution but NOT so fluent We need 3 methods to deal with cache
  • 43. Stream modeling key key key key key key FILTER AJAX CALL jso n jso n MAP key key key key key key key respons e respons e
  • 44. flatmapExample = Rx.Observable.fromEvent(input,'keyup') flatmapExample.subscribe( (result) =>{ console.log('Flatmap', result); buildList( result ) } ) more fluent Transform event to char.map((ev) => { return ev.target.value; }) Wait until we have 3 chars .filter(function(text){ return text.length >=3; }) Only perform search if this ‘search’ is unique.distinctUntilChanged() Excellent to use when coming from one stream to another .switchMap((val) => { return Rx.DOM.getJSON( 'data3.json' ); })
  • 48. retry let stream = Rx.Observable.interval(1000) .take(6); .map((n) => { if(n === 2) { throw 'ex'; } return n; }) Produce error .retry(2) Number of tries before hitting error callback stream.subscribe( (data) => console.log(data) (error) => console.log(error) 1 Emits 3 Makes x attempts before error cb is called
  • 49. retryWhen delay between attempts let stream = Rx.Observable.interval(1000) .take(6); delay, 200 ms.retryWhen((errors) => { return errors.delay(200); }) .map((n) => { if(n === 2) { throw 'ex'; } return n; }) produce an error when = 2 stream.subscribe( (data) => console.log(data) (error) => console.log(error) for those shaky connections
  • 50. What did we learn so far? We can cancel with .unsubsribe() We can retry easily A stream generates a continuous stream of values Operators manipulate either the values or the stream/s We can “patch” an erronous stream with a .catch() or Ignore a failing stream altogether with onErrorResumeNext
  • 52. What about schedulers and testing? Because scheduler has its own virtual clock Anything scheduled on that scheduler will adhere to time denoted on the clock I.e we can bend time for ex unit testing
  • 53. Marble testing Yes it has to do with marbles, essentially its visual comparison
  • 54. QUnit.test("Test simple emit 1 2 3", function(assert){ // setup const lhsMarble = '-x-y-z'; const expected = '-x-y-z'; const expectedMap = { x: 1, y: 2, z : 3 }; const lhs$ = testScheduler.createHotObservable(lhsMarble, expectedMap); const myAlgorithm = ( lhs ) => Rx.Observable .from( lhs ); const actual$ = myAlgorithm( lhs$ ); //assert testScheduler.expectObservable(actual$).toBe(expected, expectedMap); testScheduler.flush(); }); Create a hot observable from a marble pattern
  • 55. QUnit.test("Test filter", function(assert){ const lhsMarble = '-x-y-z'; const expected = '---y-'; const expectedMap = { x: 1, y: 2, z : 3 }; const lhs$ = testScheduler.createHotObservable(lhsMarble,expectedMap); const myAlgorithm = ( lhs ) => Rx.Observable .from( lhs ) .filter(x => x % 2 === 0 ); const actual$ = myAlgorithm( lhs$ ); //assert testScheduler.expectObservable(actual$).toBe(expected, expectedMap); testScheduler.flush(); }); An extra hyphen, to make time match
  • 56. Yes - means something Its a time increment
  • 57. There are other characters besides - like # = error and | = completion
  • 58. QUnit.test("Test error", function(assert){ const lhsMarble = '-#'; const expected = '#'; const expectedMap = { }; //const lhs$ = testScheduler.createHotObservable(lhsMarble, expectedMap); const myAlgorithm = ( lhs ) => Rx.Observable .from( lhs ); const actual$ = myAlgorithm( Rx.Observable.throw('error') ); //assert testScheduler.expectObservable(actual$).toBe(expected, expectedMap); testScheduler.flush(); }) Will cause an error Error will happen
  • 59. Test Summary You use a descriptive marble to define behaviour -x-y-z There are symbols that mean something like : - # |
  • 61. .then vs .subscribe getData() .then( ) getData().subscribe( ) I will keep on streaming values (data) => console.log(data), (data) => console.log(data), (err) => console.log(err) (err) => console.log(err)
  • 62. user order orderItem Fetch user Then fetch order Lastly fetch order item
  • 63. Cascading calls Response: //getUser stream .subscribe((orderItem) => { console.log('OrderItem',orderItem.id); }) { id: 11, userId : 1 }.then(getOrderByUser) .switchMap((user) => { //getOrder return Rx.Observable.of({ id : 11, userId : user.id }).delay(3000) }) { id: 123, orderId : 11 }.then(getOrderItemByOrder) .switchMap((order) => { //getOrderItem return Rx.Observable.of({ id: 114, orderId: order.id }) }) { id: 1 }getUser() var stream = Rx.Observable.of({ id : 1 }); So we can see the first user observable being dropped when user 2 is emitted
  • 64. Short word on switchMap is to ensure we throw away the other calls when a new user is em We don’t want getUser getOrderByUser getOrderItemByOrder to complete if a new user is emitted 1 2 3 2 4 5 Not continued Replaces above stream
  • 66. Cascading call wait for the first .subscribe( (data) => { console.log( 'orders', data[0] ); console.log( 'messages', data[0] ); } ) var stream = Rx.Observable.of([{ id : 1 }, { id : 2 }]); getUser() We wait for user function getOrdersAndMessages(user){ return Promise.all([ getOrdersByUser( user.id ), getMessagesByUser( user.id ) ]) } .then(getOrdersAndMessages) stream.switchMap((user) => { return Rx.Observable.forkJoin( Rx.Observable.of([ { id: 1, userId : user.id } ]).delay(500), // orders Rx.Observable.of([ { id: 100, userId : user.id } ]).delay(1500) //messages ) }) Calls to orders and message can happen in parallel Orders,Messages arrive at the same time
  • 67. Last summary We can use schedulers to easily test our code Cascading calls can easily be setup switchMap over flatMap when doing ajax calls because we need it to abandon the stream if the first condition change
  • 68. Further Reading angular.io/resources Rxjs Ultimate https://github.com/ReactiveX/rxjs Free book Official docs