39
Functional Reactive Programming in JS Mario Zupan @mzupzup Stefan Mayer @stefanmayer13

Functional Reactive Programming with RxJS

Embed Size (px)

DESCRIPTION

Talk by @mzupzup and @stefanmayer13 about Functional Reactive Programming in JavaScript at the 4th grazjs meetup (http://www.meetup.com/grazjs/).

Citation preview

Page 1: Functional Reactive Programming with RxJS

Functional Reactive

Programming in JS

Mario Zupan@mzupzup

Stefan Mayer@stefanmayer13

Page 2: Functional Reactive Programming with RxJS

Who are we?

@stefanmayer13 @mzupzup

2

Page 3: Functional Reactive Programming with RxJS

Motivation

■ Technology stack re-evaluation

■ Lessons learned

■ Functional Programming

■ QCon NYC

[1]

3

Page 4: Functional Reactive Programming with RxJS

What is Functional Reactive

Programming?

4

Page 5: Functional Reactive Programming with RxJS

Reactive Manifesto

[2]

5

Page 6: Functional Reactive Programming with RxJS

Reactive Manifesto

? ?

? ? [2]

6

Page 7: Functional Reactive Programming with RxJS

Functional Programming

■ Evaluation of mathematical functions

■ Avoid mutable state

■ Referential transparency

■ Avoid side-effects

■ Reusable functions over reusable object

■ Function composition over object

composition

[1]

7

Page 8: Functional Reactive Programming with RxJS

Functional Programming

■ map

■ filter

■ mergeAll

■ reduce

■ zip

[3]

[4] 8

Page 9: Functional Reactive Programming with RxJS

var data = [1, 2, 3, 4, 5];

var numbers = data.map(function (nr) {

return nr + 1;

});

// numbers = [2, 3, 4, 5, 6]

9

Page 10: Functional Reactive Programming with RxJS

var data = [1, 2, 3, 4, 5, 6, 7];

var numbers = data.filter(function (nr) {

return nr % 2 === 0;

});

// numbers = [2, 4, 6]

10

Page 11: Functional Reactive Programming with RxJS

var data = [1, 2, 3, 4, 5, 6, 7];

var numbers = data.map(function (nr) {

return nr + 1;

}).filter(function (nr) {

return nr % 2 === 0;

});

// numbers = [2, 4, 6, 8]11

Page 12: Functional Reactive Programming with RxJS

var data = [[1, 2], [3, 4], 5, [6], 7, 8];

var numbers = data.mergeAll();

// numbers = [1, 2, 3, 4, 5, 6, 7, 8]

12

Page 13: Functional Reactive Programming with RxJS

var data = [{

numbers: [1, 2]

}, {

numbers: [3, 4]

}];

var numbersFlatMap = data.flatMap(function (object) {

return object.numbers;

});

// numbersMap = [[1, 2], [3, 4]]

// numbersFlatMap = [1, 2, 3, 4]

13

Page 14: Functional Reactive Programming with RxJS

var data = [1, 2, 3, 4];

var sum = data.reduce(function(acc, value) {

return acc + value;

});

// sum = 10

14

Page 15: Functional Reactive Programming with RxJS

var data = [5, 7, 3, 4];

var min = data.reduce(function(acc, value) {

return acc < value ? acc : value;

});

// min = 3

15

Page 16: Functional Reactive Programming with RxJS

var array1 = [1, 2, 3];

var array2 = [4, 5, 6];

var array = Array.zip(array1, array2,

function(left, right) {

return [left, right];

});

// array = [[1, 4], [2, 5], [3, 6]]16

Page 17: Functional Reactive Programming with RxJS

Reactive Programming

■ Asynchronous data streams

■ Everything is a stream

● click events

● user inputs

● data from a server

■ streams rock!

17

Page 18: Functional Reactive Programming with RxJS

Reactive Programming

[5]18

Page 19: Functional Reactive Programming with RxJS

F + R + P

■ Powerful composition and aggregation of

streams

■ Good fit for concurrent and event-driven

systems

■ Declarative

■ Easy to test

[6]19

Page 20: Functional Reactive Programming with RxJS

Observables

■ Stream of data over time

■ Hot vs cold observables

■ Asynchronous

■ Lazy

■ queryable, bufferable, pausable…

■ more than 120 operations

[7]

20

Page 21: Functional Reactive Programming with RxJS

Observable Creation

Rx.Observable.fromArray([1, 2, 3]);

Rx.Observable.fromEvent(input, 'click');

Rx.Observable.fromEvent(eventEmitter, 'data', fn);

Rx.Observable.fromCallback(fs.exists);

Rx.Observable.fromNodeCallback(fs.exists);

Rx.Observable.fromPromise(somePromise);

Rx.Observable.fromIterable(function*() {yield 20});21

Page 22: Functional Reactive Programming with RxJS

var range = Rx.Observable.range(1, 3); // 1, 2, 3

var range = range.subscribe(function(value) {},function(error) {},function() {}

);

Observable Basics

optional

22

Page 23: Functional Reactive Programming with RxJS

var range = Rx.Observable.range(1, 10) // 1, 2, 3 ...

.filter(function(value) { return value % 2 === 0; })

.map(function(value) { return "<span>" + value + "</span>"; })

.takeLast(1);

var subscription = range.subscribe(

function(value) { console.log("last even value: " + value); });

// "last even value: <span>10</span>"

Observable Basics

23

Page 24: Functional Reactive Programming with RxJS

Cold Observables

[8]

24

Page 25: Functional Reactive Programming with RxJS

Hot Observables

[9]

25

Page 26: Functional Reactive Programming with RxJS

Autocomplete

● Multiple requests

● Async results

● Race conditions

● State

● ...

[10]

26

Page 27: Functional Reactive Programming with RxJS

Autocomplete 1/2

var keyup = Rx.Observable.fromEvent(input, 'keyup')

.map(function (e) {

return e.target.value; // map to text

})

.filter(function (input) {

return input.length > 2; // filter relevant values

})

.debounce(250)

27

Page 28: Functional Reactive Programming with RxJS

.distinctUntilChanged() // only if changes

.flatMapLatest(doAsyncSearch() // do async search on server

.retry(3))

.takeUntil(cancelStream) // cancel stream

.subscribe(

function (data) { // do UI stuff },

function (error) { // do error handling }

);

Autocomplete 2/2

28

Page 29: Functional Reactive Programming with RxJS

Drag & Drop 1/2

var mousedown = Rx.Observable.fromEvent(dragTarget, 'mousedown');

var mousemove = Rx.Observable.fromEvent(document, 'mousemove');

var mouseup = Rx.Observable.fromEvent(dragTarget, 'mouseup');

[11]

29

Page 30: Functional Reactive Programming with RxJS

mousedown.flatMap(function (md) {

// get starting coordinates

var startX = md.offsetX, startY = md.offsetY;

return mousemove.map(function (mm) {

// return the mouse distance from start

return {left: mm.clientX - startX, top: mm.clientY - startY };

}).takeUntil(mouseup);

}).subscribe(function (pos) {

// do UI stuff

}); [11]

30

Page 31: Functional Reactive Programming with RxJS

Some Cool Stuff on Observables

.bufferWithTime(500)

.pausable(pauser), .pausableBuffered(..)

.repeat(3)

.skip(1), skipUntilWithTime(..)

.do() // for side-effects like logging

.onErrorResumeNext(second) // resume with other obs

.window() // project into windows

.timestamp() // add time for each value

.delay() 31

Page 32: Functional Reactive Programming with RxJS

RxJS

Supported

■ IE6+

■ Chrome 4+

■ FireFox 1+

■ Node.js v0.4+

Size (minified & gzipped):

■ all - 23,1k

■ lite - 13,5k

■ compat - 12,5k

■ ES5 core - 12k

[12]

32

Page 33: Functional Reactive Programming with RxJS

Framework Bridges

■ AngularJS

■ ReactJS

■ jQuery

■ ExtJS

■ NodeJS

■ Backbone

■ ...

33

Page 34: Functional Reactive Programming with RxJS

Companies using Rx in Production

[13]

34

Page 35: Functional Reactive Programming with RxJS

Alternatives to RxJS

■ BaconJS

■ Kefir

■ (Elm)

35

Page 36: Functional Reactive Programming with RxJS

Conclusion

■ There is a learning curve

■ Great abstraction for async & events

■ Improves

● Readability

● Reusability

● Scalability

■ Both on the front- and backend

36

Page 37: Functional Reactive Programming with RxJS

Learning RxJS

■ RxKoans

○ https://github.com/Reactive-Extensions/RxJSKoans

■ learnRx

○ https://github.com/jhusain/learnrx

■ The Introduction to Reactive Programming you've been

missing

○ https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

■ rxMarbles

○ http://rxmarbles.com/

37

Page 38: Functional Reactive Programming with RxJS

Image references■ 1 - http://www.ylies.fr/

■ 2 - http://www.reactivemanifesto.org

■ 3 - http://reactivex.io/

■ 4 - https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/

■ 5 - http://buildstuff14.sched.org/event/9ead0e99b3c1c0edddec6c7c8d526125#.VHEgq5PF-kQ

■ 6 - http://www.cclscorp.com

■ 7 - http://www.pharmmd.com/

■ 8 - http://blogs.msdn.com/

■ 9 - http://blogs.msdn.com/

■ 10 - https://www.google.at

■ 11 - http://dockphp.com/

■ 12 - http://www.thechrisyates.com/

■ 13 - http://www.reactivex.io

■ 14 - http://www.quickmeme.com/

38

Page 39: Functional Reactive Programming with RxJS

Thank you

@stefanmayer13

@mzupzup

[14]

39