Slide 1

Slide 1 text

An in-depth look at debugging RxJS code Mark van Straten @markvanstraten q42.com

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Why not use callbacks?

Slide 8

Slide 8 text

TESTABILITY

Slide 9

Slide 9 text

Enter RXJS

Slide 10

Slide 10 text

no defer() around promise, retry fails OOM due to concatMap non-completing Observables OOM due to memory leak in Rx library switchMap().catch() returns Observable.empty(), stream completes Promise executes without subscription (Eager) Duplicate streams due to not using share() Observable not completing due to wrongly coded completion logic Error handling breaking main observable flow scheduler not passed to transformation func causing test to run in real time OOM zip() fast and slow emitting stream no catch() breaking the stream infinite retry() logic switch of() and from() toPromise() on never completing stream BUGS EVERYWHERE subscribed twice to a cold stream made a filter statement with 5000 subscribers timer() arguments - start direct, once, repeat always? mergeMap without concurrency arg error crashing stream, forgot to add subscribe() logging forgot to subscribe() created an exception inside subscribe() logic subscribe() statement inside other stream

Slide 11

Slide 11 text

WHERE DO THE BUGS HIDE?

Slide 12

Slide 12 text

VALUES LIFECYCLE TRANSFORMATIONS

Slide 13

Slide 13 text

DEBUGGING VALUES

Slide 14

Slide 14 text

OUTPUT LOGGING const chars = "abc".split(""); Observable.of(chars) .do(val !=> console.log('next: ' + val)) .subscribe(); next: ["a","b","c"]

Slide 15

Slide 15 text

BREAKPOINTS

Slide 16

Slide 16 text

MEMORY DUMPS const chars = "abcdefghijk".split(""); Observable.from(chars) .scan((acc, curr) !=> curr + acc, "") .subscribe(console.log);

Slide 17

Slide 17 text

DEBUGGING LIFECYCLE

Slide 18

Slide 18 text

DRAWING DEPENDENCY GRAPHS

Slide 19

Slide 19 text

const chars = Observable .from("abc".split("")) .debug('chars-source-stream', false); const capitals = chars .map(char !=> char.toUpperCase()); const pairs = chars .zip(capitals) .subscribe(console.log);

Slide 20

Slide 20 text

[chars-source-stream] subscribed [chars-source-stream] completed [chars-source-stream] unsubscribed [chars-source-stream] subscribed [ 'a', 'A' ] [ 'b', 'B' ] [ 'c', 'C' ] [chars-source-stream] completed [chars-source-stream] unsubscribed

Slide 21

Slide 21 text

const chars = Observable .from("abc".split("")) .debug('chars-source-stream', false); const charsShared = charsCold .share();

Slide 22

Slide 22 text

[chars-source-stream] subscribed [ 'a', 'A' ] [ 'b', 'B' ] [ 'c', 'C' ] [chars-source-stream] completed [chars-source-stream] unsubscribed

Slide 23

Slide 23 text

LIFECYCLE EVENTS

Slide 24

Slide 24 text

function debug (this: Observable, identifier: string): Observable { return Observable.empty() .do(_ !=> {}, undefined, () !=> console.log(`[${identifier}] subscribed`)) .concat( this.do( (val) !=> console.log(`[${identifier}] nextVal: ${val}`), (err) !=> console.log(`[${identifier}] error: ${err.message}`), () !=> console.log(`[${identifier}] completed`) ) ) .finally(() !=> console.log(`[${identifier}] unsubscribed`)); };

Slide 25

Slide 25 text

Stream thrown error logs: [1] subscribed [1] unsubscribed Stream completed [2] subscribed [2] completed [2] unsubscribed Unsubscribe before completion [3] subscribed [3] unsubscribed

Slide 26

Slide 26 text

DEBUGGING TRANSFORMATIONS

Slide 27

Slide 27 text

Observable.interval(100) .concatMap(i !=> Observable.of(i).delay(1000))

Slide 28

Slide 28 text

OOM

Slide 29

Slide 29 text

stockTicker() : Observable { return Observable.interval(100) .concatMap(_ !=> fetchPricesFromSlowServer()); }

Slide 30

Slide 30 text

uploadImages(path: string): Observable { return readDir(path, "*.png") .mergeMap(image !=> uploadImage(image)); }

Slide 31

Slide 31 text

429 Too Many Requests

Slide 32

Slide 32 text

INCORRECT OPERATOR

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

MARBLE DIAGRAMS

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

RXFIDDLE

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

RXSPY

Slide 39

Slide 39 text

var spy = RxSpy.create(); (function () { var interval = new Rx.Observable .interval(2000) .tag("interval"); var people = interval .map((value) !=> { const names = ["alice", "bob"]; return names[value % names.length]; }) .tag("people") .subscribe(); })(); !

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

!// create repl for rxspy usage after app code const rxspy = create(); import * as repl from 'repl'; const replServer = repl.start({ prompt: "rx-spy debugger > ", }); replServer.context.rxspy = rxspy;

Slide 42

Slide 42 text

rx-spy debugger > rxspy.log('people') [Function] rx-spy debugger > Tag = people; notification = next; value = alice Tag = people; notification = next; value = bob Tag = people; notification = next; value = alice Tag = people; notification = next; value = bob

Slide 43

Slide 43 text

HOW TO PREVENT THESE BUGS

Slide 44

Slide 44 text

TYPESCRIPT

Slide 45

Slide 45 text

KISS

Slide 46

Slide 46 text

return readdir(path) .filter(file !=> file.mimeType !!=== "image/png") .filter(file !=> file.fileSize < 10 * 1024 ) .catch((err) !=> { console.log("reading images failed: " + err.message) return Observable.empty(); }) .mergeMap(file !=> { return uploadImage(path) .retryWhen(err !=> err .delay(500) .take(3) .concat( Observable.throw(new Error('upload

Slide 47

Slide 47 text

readImagesInDir(path) .mergeMap(image !=> uploadImageToCdn(image.path)) .mergeMap(uploadRes !=> saveCdnUrlInDb(uploadRes))

Slide 48

Slide 48 text

DOCUMENT STREAMS

Slide 49

Slide 49 text

/** * persists to our local SQL instance where the * file with the given path has been uploaded * to our content delivery network * * side-effects: mutates the database * hot/cold: cold * lifecycle: Error: Has built in retry logic with * small backoff (500ms). After 3 * attempts will throw error. * Completes: after url has been * persisted * * @param uploadResult !*/ function saveCdnUrlInDb(uploadResult: { path: string,

Slide 50

Slide 50 text

TESTS

Slide 51

Slide 51 text

RECAP

Slide 52

Slide 52 text

Conventional debugging techniques still apply

Slide 53

Slide 53 text

.do(), .debug() and dependency graphs are low barrier ways to gain insights in values and stream lifecycle

Slide 54

Slide 54 text

rxfiddle and rx-spy are very helpful to learn how streams transform values and debug these

Slide 55

Slide 55 text

But above all; Prevent bugs using typescript, code hygiene and tests

Slide 56

Slide 56 text

IS RXJS WORTH IT?

Slide 57

Slide 57 text

–Marie Curie "I was taught that the way of progress was neither swift nor easy."

Slide 58

Slide 58 text

THANKS FOR LISTENING @markvanstraten q42.com

Slide 59

Slide 59 text

REFERENCES • https://gist.github.com/crunchie84/f212e3674ea02480431716bebd214ea3 (debug operator) • https://rxfiddle.net/ • https://cartant.github.io/rxjs-spy/ • https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 • https://tech.residebrokerage.com/debugging-node-js-memory-problems- d450787d9253