Reactive Programming with JavaScript

63
Reactive Programming with JavaScript @giorgionatili

Transcript of Reactive Programming with JavaScript

Page 1: Reactive Programming with JavaScript

Reactive Programming with JavaScript

@giorgionatili

Page 2: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

$ whoami

• Lead Software Engineer (McGraw-Hill Education)

• Community fellow since 2004 (Codeinvaders)

• Open source fanatic

• Founder of Mobile Tea

Page 3: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Mobile Tea

• A free community

• A movement around the two continents

• A place to have fun while learning

Page 4: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Supporters

http://careers.mheducation.com https://dev.twitter.com

Page 5: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Agenda• An Overview of JavaScript past and future

• Reactive Programming in a Nutshell

• What is Functional Programming

• Asynchronous JavaScript Applications

• Redux, Angular 2 and Reactive Programming

Page 6: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

JavaScript

Page 7: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Why people hate it

• Lack of code organization, spaghetti code everywhere and abuse of globals

• Weird inheritance chain (aka prototype property)

• Callbacks are not straight forward to digest

• The mutability of the this keyword

Page 8: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Why people love it

• It has a rather low entry barrier; people can start coding and get results quickly

• It’s full of (legacy) examples to start with

• JavaScript is suited for the rest of us, continuously learning web hackers not having a PhD in CS

Page 9: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

It’s your choice

Page 10: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

JS, the New Assembly

• Everybody loves it but nobody wants really write it

• Some of the internals are hidden by popular frameworks (and people is happy about it)

• Only recently syntax and features get a relevant improvement (ES2015)

Page 11: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

JS, What’s Next

Page 12: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Long Story Short• ECMAScript (ES) standardization started in 1996

• ES 3 was published in 1999 (the age of browsers war)

• ES 5 was published in 2009 (adoption started late 2011)

• ES6 was published in 2015 (early adoption)

• ES Next https://babeljs.io/docs/plugins/

Page 13: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

What’s Changing

• The way of thinking in JavaScript (modules, scopes, arrow functions, classes, etc.)

• The support for asynchronous programming (async and await, promises, yield, etc.) tasks

• Math, Number, String, Array and object APIs re-evolution

Page 14: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Array & Arrow Functions

Array.from(document.querySelectorAll('*')) // Returns a real Array Array.of(1, 2, 3) // Similar to new Array(…),

[0, 0, 0].fill(7, 1) // [0,7,7] [1, 2, 3].find(x => x == 3) // 3 [1, 2, 3].findIndex(x => x == 2) // 1

[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2] ["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"] ["a", "b", "c"].keys() // iterator 0, 1, 2 ["a", "b", "c"].values() // iterator "a", "b", "c"

Page 15: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Classes & Inheritance// Pseudo-code of Array class Array { constructor(...args) { /* ... */ } static [Symbol.create]() { // Install special [[DefineOwnProperty]] // to magically update 'length' } }

// User code of Array subclass class MyArray extends Array { constructor(...args) { super(...args); } }

Page 16: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Proxy Objects

var target = {}; var handler = { get: function (receiver, name) { return `Hello, ${name}!`; } };

var p = new Proxy(target, handler); p.world === 'Hello, world!';

custom behavior for fundamental operations

Page 17: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Huge Impact

• Many new features and emerging standards

• Early browsers adoptions through transpilers (babeljs, traceur, etc.)

• Frameworks are adopting it (e.g. Angular 2, EmberJS, ReactJS, etc.)

Page 18: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Now Everything is Possible

Page 19: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Reactive Programming

Page 20: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

In a Nutshell• Is a programming paradigm oriented around data

flows

• Variables and property values get updated at runtime and the system is notified about changes

• Is similar to the well known observer pattern

• Supports different programming paradigms like Imperative, Object Oriented and Functional

Page 21: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Why It Matters• Enables developers creating data streams of

anything, not just from click and hover events

• Data streams emit events that can be handled asynchronously

• Data streams are data structures and then can be filtered

• Extends the asynchronous event engine of JavaScript to data flows

Page 22: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Reactive Systems

Page 23: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Reactive Systems• Responsive: the system responds in a timely manner

to data stream changes

• Elastic: the system stays responsive under varying workload

• Message Driven: the system relies on asynchronous not blocking message-passing

• Resilient: the system stays responsive in the face of failure (error handling)

Page 24: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Functional Programming

Page 25: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

FP definition relies on foreboding statements like “functions as first-class objects” and “eliminating side

effects”

Definition

Page 26: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

• All of your functions must accept at least one argument

• All of your functions must return data or another function

• No loops! (What???)

Getting Started

Page 27: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

In Practicefunction totalForArray(currentTotal, arr) { currentTotal += arr[0];

// I am not using Array.shift on because // we're treating arrays as immutable. var remainingList = arr.slice(1);

// This function calls itself with the remainder of the list, and the // current value of the currentTotal variable if(remainingList.length > 0) { return totalForArray(currentTotal, remainingList); } // Unless the list is empty, in which case we return // the currentTotal value else { return currentTotal; } }

Page 28: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

• First Class Functions: functions treated as objects, can be passed as arguments and returned as values

• Pure Functions: a function that doesn’t depend on and doesn’t modify the states of variables out of its scope

• Immutable Variables: a variable that preserves its original value after a mutation

Things I Like

Page 29: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

First Class Functions

function analyticsHandler(e) { ...//perform some analytics. }

$('form').on('submit',analyticsHandler);

You really used jQuery? Yes, I am sorry! :)

Page 30: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Pure Functionsvar values = { a: 1 };

function impureFunction ( items ) { var b = 1;

items.a = items.a * b + 2; return items.a; } var c = impureFunction( values ); // Now `values.a` is 3

function pureFunction ( a ) { var b = 1;

a = a * b + 2;

return a; } var d = pureFunction( values.a ); // Values.a is not modified

Page 31: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Immutable Variables

var arr = new ImmutableArray([1, 2, 3, 4]); var v2 = arr.push(5);

arr.toArray(); // [1, 2, 3, 4] v2.toArray(); // [1, 2, 3, 4, 5]

Page 32: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

• The data should be immutable (creating new data structures instead of modifying the ones that already exist)

• The app and its components should be stateless (no memory of previous execution)

App Perspective

Page 33: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

It’s Not a Buzzword

Page 34: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

• This book gives a lucid and thorough account of the concepts and techniques used in modern functional programming languages. Standard ML is used for notation, but the examples can be easily adapted to other functional languages.

• Originally published: January 1, 1989

• Author: Chris Reade

It’s a Science

Page 35: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Functional Reactive Programming

• Is a programming paradigm for reactive programming to which are applied the building blocks of functional programming (e.g. map, reduce, filter, merge, etc.)

• It’s implemented in JavaScript by popular libraries such as bacon.js and RxJS (sounds familiar Java developers?)

Page 36: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Bacon.js

var up = $('#up').asEventStream('click'); var down = $('#down').asEventStream('click');

var counter = // map up to 1, down to -1 up.map(1).merge(down.map(-1)) // accumulate sum .scan(0, function(x,y) { return x + y });

// assign the observable value to jQuery property text counter.assign($('#counter'), 'text');

Page 37: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Asynchronous

Page 38: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

The Callback Hellvar p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory}); p_client.open(function(err, p_client) { p_client.dropDatabase(function(err, done) { p_client.createCollection('test_custom_key', function(err, collection) { collection.insert({'a':1}, function(err, docs) { collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) { cursor.toArray(function(err, items) { test.assertEquals(1, items.length);

// Let's close the db p_client.close(); }); }); }); }); }); });

Page 39: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

ES6 Promisesvar promise = new Promise(function(resolve, reject) { // do a thing, possibly async, then…

if (/* everything turned out fine */) { resolve("Stuff worked!"); } else { reject(Error("It broke")); } });

promise.then(function(result) { console.log(result); // "Stuff worked!" }, function(err) { console.log(err); // Error: "It broke" });

Page 40: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Async and Awaitvar request = require('request'); function getQuote() { var quote; return new Promise(function(resolve, reject) { request('http://ron-swanson-quotes.com/v2/quotes', function(error, response, body) { quote = body; resolve(quote); }); }); } async function main() { var quote = await getQuote(); console.log(quote); } main(); console.log('Ron once said,');

Page 41: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Asynchronous(made cool!)

Page 42: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Redux in a Nutshell• Redux is a predictable state container for JavaScript

applications

• Instead of mutating the state directly, you specify the mutations you want to happen with plain objects called actions

• Then you write a special function called a reducer to decide how every action transforms the entire application’s state

• You should always return the state of the app

Page 43: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Redux Actions“Actions are payloads of information that send data

from your application to your store”

{ type: 'ADD_TODO', text: 'Use Redux' } { type: 'REMOVE_TODO', id: 42 } { type: 'LOAD_ARTICLE', response: { ... } }

Page 44: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Redux Reducers

“Actions describe the fact that something happened, then a reducer handle the event and eventually

update the app state”

Page 45: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Redux Reducersimport * as TodoActions from './todoActions';

const initialState = { todos: [], currentFilter: 'SHOW_ALL' }

export function rootReducer(state = initialState, action){ switch (action.type) { case TodoActions.ADD_TODO: return { todos: state.todos.concat({ id: action.id, text: action.text, completed: action.completed }), currentFilter: state.currentFilter }; case TodoActions.TOGGLE_TODO: return {}; // Continue... } }

Page 46: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Redux Stores“A Redux store is the object that brings together actions

and reducers offering a centralized way to dispatch actions and access the app state”

import { createStore } from 'redux' import todoApp from './reducers' import { addTodo} from './actions'

let store = createStore(todoApp)

// Log the initial state console.log(store.getState())

// Dispatch some actions store.dispatch(addTodo('Learn about actions'))

Page 47: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Redux Data Flow• You call store.dispatch(action)

• The store calls the reducer function you gave it

• The root reducer may combine the output of multiple reducers into a single state tree

• The store saves the complete state tree returned by the root reducer

Page 48: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

How it Sounds?

Page 49: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Angular 2

Page 50: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Tech Stack• TypeScript

• RxJS

• JSPM or WebPack

• Grunt (seriously?!?) or Gulp

• Karma + Jasmine or (Mocha + Chai)

Page 51: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

TypeScript

• A super set of JavaScript developed by Microsoft

• Implements classes, interfaces, inheritance, strict data typing, private properties and methods, etc.

• Angular Team choice for the next version of Angular (Microsoft and Google are now buddies!)

Page 52: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

RxJS

• A reactive streams library that allows you to work with asynchronous data streams

• Combines Observables and Operators so we can subscribe to streams and react to changes using composable operations

Page 53: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

RxJS, hello world!

$scope.counter = 0; rx.Observable .interval(1000) .take(3) .safeApply($scope, function(x) { $scope.counter = x; }) .subscribe(); // shows 0, 1, 2

Page 54: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Integrating Redux$ npm install angular2-redux

import {AppStore} from "angular2-redux"; import {bootstrap} from "angular2/platform/browser"; // create factory to be called once angular has been bootstrapped const appStoreFactory = () => { let reduxAppStore; // create redux store // ... return new AppStore(reduxStore); }; // bootstrap angular bootstrap(MyAppComponent,[provide(AppStore, { useFactory: appStoreFactory })]);

Page 55: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Demohttps://plnkr.co/edit/3mhKoOOAKJp27E2FpIOq

Page 56: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Wait a second…

Page 57: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Reactive Programming, functional programming and OOP?

Page 58: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Page 59: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Using Functions Properly• Keep your functions pure

• Use your functions as arguments

• Write small reusable functions

• Return functions if needed

• Always return a value

Page 60: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Taking Advantages from RxJSimport {Http} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {Observer} from 'rxjs/Observer'; import 'rxjs/add/operator/share'; import {Todo} from 'app/interfaces';

export class TodosService { todos$: Observable<Todo[]>; private _todosObserver: Observer<Todo[]>; private _dataStore: { todos: Todo[] }; constructor(private _http: Http) { // Create Observable Stream to output our data this.todos$ = new Observable(observer => this._todosObserver = observer).share(); this._dataStore = { todos: [] }; } }

Page 61: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Embracing Redux Data Flows

• Decouple your dependencies by implementing event driven architecture

• Keep the app state predictable by returning a new state

Page 62: Reactive Programming with JavaScript

@giorgionatili // #mobiletea

Questions and Answers

Page 63: Reactive Programming with JavaScript

–Giorgio Natili

“Keep calm and rock ‘n roll the Codemotion!”

Thanks!