Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to FRP

Introduction to FRP

An introduction to Functional Reactive Programming - presented at 9th GreeceJS meetup

Stratos Pavlakis

July 21, 2015
Tweet

More Decks by Stratos Pavlakis

Other Decks in Programming

Transcript

  1. Functional Reactive Programming
    in Javascript

    View Slide

  2. whoami
    Stratos Pavlakis
    Workable UI Tech Lead
    [email protected]
    th3hunt
    FRP newbie!

    View Slide

  3. what’s FRP?

    View Slide

  4. let’s begin with

    View Slide

  5. http://www.reactivemanifesto.org/
    Responsive Message Driven
    Resilient
    Elastic

    View Slide

  6. sweet dreams

    View Slide

  7. so better start with

    View Slide

  8. reactive paradigm
    var b = 1, c = 1;
    var a = b + c; // a == 2
    b = 10;
    ● // a == ?
    ● // imperative paradigm => a == 2
    ● // reactive paradigm => a == 11

    View Slide

  9. front end development
    is it synchronous or asynchronous?

    View Slide

  10. ● User Input
    ● AJAX
    ● Web Sockets / SSE
    ● Web Workers
    ● Animations
    ● Cross origin frame communication
    ● Updating the DOM
    we deal with

    View Slide

  11. ● User Input
    ● AJAX
    ● Web Sockets / SSE
    ● Web Workers
    ● Animations
    ● Cross origin frame communication
    ● Updating the DOM
    most are async!

    View Slide

  12. tools we use

    View Slide

  13. callbacks
    var el = document.getElementById("my-button");
    el.addEventListener("click", function () {
    console.log(‘my button was clicked’);
    });

    View Slide

  14. promises
    $http(endpoint1)
    .get({q: ‘frp’})
    .then(function (data) {
    console.log(‘We got data back from ajax %s’, data);
    })
    .then(function (data) {
    return $http(endpoint2).get({id: data.id});
    })

    View Slide

  15. generators in ES7
    async(function main() {
    var result1 = await request( "http://endpoint.1" );
    var data = JSON.parse( result1 );
    var result2 = await request( "http://endpoint.2?id=" +
    data.id );
    var resp = JSON.parse( result2 );
    console.log( "Value: " + resp.value );
    })

    View Slide

  16. problems
    ● callback hell
    ● try / catch (except for generators)
    ● memory leaks
    ● reduced composability

    View Slide

  17. event driven programming
    we react to events

    View Slide

  18. is reason about event streams
    what we’re really trying to do

    View Slide

  19. any number of values
    Array
    over any amount of time
    f(time) / async
    an event stream would be

    View Slide

  20. first class citizen of FRP
    observable

    View Slide

  21. Observer
    Iterator
    Gang of Four - Design Patterns
    ES6 EventEmitter

    View Slide

  22. array VS event

    View Slide

  23. array === collection

    View Slide

  24. events === collection

    View Slide

  25. collections are iterable

    View Slide

  26. observable === collection + time

    View Slide

  27. observable API
    var subscription = myObservable.subscribe(function (val) {
    console.log(‘Next: %s’, val);
    });

    View Slide

  28. from the EventEmitter?
    so… how is that different

    View Slide

  29. we know when it’s done
    var subscription = myObservable.subscribe(
    onNext,
    onError,
    onCompleted
    );
    like
    promises

    View Slide

  30. we got set operators
    ● map
    ● flatMap
    ● reduce
    ● merge
    ● concat
    ● zip

    View Slide

  31. more operators
    ● debounce
    ● buffer
    ● skipUntil
    ● flatMapLatest
    ● combineLatest
    ● switch
    ● retry

    View Slide

  32. observables can model
    ● mouse clicks
    ● key presses
    ● scrolling
    ● animations
    ● AJAX Polling, Web Sockets
    ● timers
    ● even… constants

    View Slide

  33. operators
    http://rxmarbles.com/

    View Slide

  34. filter

    View Slide

  35. debounce

    View Slide

  36. distinctUntilChanged

    View Slide

  37. takeUntil

    View Slide

  38. example
    please!

    View Slide

  39. mousedown.flatMap((md) => {
    var startX = md.offsetX, startY = md.offsetY;
    return mousemove.map((mm) => {
    return {
    left: mm.clientX - startX,
    top: mm.clientY - startY
    };
    }).takeUntil(mouseup);
    }).subscribe((pos) => {
    dragTarget.style.top = pos.top + 'px';
    dragTarget.style.left = pos.left + 'px';
    });
    drag & drop

    View Slide

  40. Autocomplete
    yes I know, the classic example

    View Slide

  41. requirements
    ● filter queries
    ● throttle requests
    ● retry (overcome network glitches)
    ● avoid duplicate requests
    ● match results to latest query
    ● abort no longer valid requests

    View Slide

  42. keyup => results
    var keyPress = $('#search').keyupAsObservable();
    .keyPress.map((ev) => { return ev.target.value; })
    .filter((text) => { return text.length > 3; })
    .debounce(500)
    .distinctUntilChanged()
    .flatMapLatest(search.retry(3).takeUntil(keyPress))
    .map((d) => { return d.response[1]; })
    .subscribe(showResults, showError);
    throttling
    no duplicate requests
    filtering
    match/abort
    response/results

    View Slide

  43. gets even better

    View Slide

  44. things we can do
    ● cancel (can’t do with Promises)
    ● be lazy until a subscriber subscribes (cold)
    ● setup datasource on first subscription
    ● teardown datasource on disposal

    View Slide

  45. not convinced yet?

    View Slide

  46. observable future
    ● TC39 proposal to add to ES7
    ○ https://github.com/zenparsing/es-observable
    ● Angular 2 first class support
    ● ReactJS first class support

    View Slide

  47. http://victorsavkin.com/post/108837493941/better-support-for-functional-programming-in

    View Slide

  48. Rx in production

    View Slide

  49. still...
    ● steep learning curve
    ● old habits die hard
    ● tricky to work with classic MV*
    ● poor/difficult documentation (is getting better)

    View Slide

  50. libraries

    View Slide

  51. ● Rx.js (port of Reactive Extensions to JS)
    ● Bacon.js
    ● Kefir (faster bacon :)

    View Slide

  52. origins

    View Slide

  53. Microsoft Research
    ● A Brief Introduction to ActiveVRML - Conan Elliott
    ● Functional Reactive Animations - Conan Elliott & Paul
    Hudak

    View Slide

  54. resources
    ● Fran Tutorial - http://conal.net/fran/tutorial.htm
    ● Simply Reactive - http://conal.net/papers/simply-reactive/
    ● Reactive Extensions - https://github.com/Reactive-Extensions/RxJS
    ● BaconJS - https://baconjs.github.io/
    ● Async JavaScript with Reactive Extensions (Jafar Husain)
    ○ https://www.youtube.com/watch?v=XRYN2xt11Ek
    ● RxJS at Modern Web UI (Ben Lesh)
    ○ https://www.youtube.com/watch?v=yk_6eU3Hcwo
    ● http://www.slideshare.net/stefanmayer13/functional-reactive-programming-with-rxjs
    ● https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
    ● RxJSKoans - https://rxkoans.codeplex.com/
    ● RxMarbles - http://rxmarbles.com/
    ● Reactive programming and MVC (Aaron Stacy)
    ○ http://aaronstacy.com/writings/reactive-programming-and-mvc/

    View Slide

  55. View Slide

  56. Questions?

    View Slide