4. REACTIVE EXTENSIONS FOR JAVASCRIPT
FUNCTIONAL PROGRAMMING
▸ Functional programming is a programming paradigm
that treats computation as the evaluation of mathematical
functions and avoids changing-state and mutable data. It is
a declarative programming paradigm, which means
programming is done with expressions or declarations
instead of statements.
5. REACTIVE EXTENSIONS FOR JAVASCRIPT
IMPERATIVE VS DECLARATIVE PROGRAMMING
function getAdmins(users) {
const admins = [];
for (let i = 0; i < users.length; i++) {
const currentUser = users[i];
if (!currentUser.isAdmin) { continue; }
admins.push(currentUser);
}
return admins;
}
Imperative programming focuses on describing how a
program operates.
function getAdmins(users) {
return users.filter(
currentUser => currentUser.isAdmin
);
}
Declarative programming focuses on expressing the logic
of a computation without describing its control flow.
6. REACTIVE EXTENSIONS FOR JAVASCRIPT
FUNCTIONAL CONCEPTS
▸ Pure Functions
▸ Composition
▸ Immutability
▸ Higher-order functions (Functions as first-class citizens)
▸ Currying and Partial Application - translating the evaluation of a function that
takes multiple arguments into evaluating a sequence of functions.
▸ Lazy evaluation - evaluate when needed.
7. REACTIVE EXTENSIONS FOR JAVASCRIPT
REFERENTIAL TRANSPARENCY
▸ An expression is called referentially transparent if it can be replaced with its
corresponding value without changing the program's behaviour. This requires
that the expression is pure, that is to say the expression value must be the same
for the same inputs and its evaluation must have no side effects.
8. REACTIVE EXTENSIONS FOR JAVASCRIPT
FUNCTIONAL PROGRAMMING ADVANTAGES
▸ Cleaner Code - Easy to test, debug and reason about (no side effects).
▸ Modularity - Breaking large problems into small parts.
▸ Reusability - Pure functions can be reused and composed.
▸ Efficiency - Lazy Evaluation (evaluate when needed)
12. REACTIVE EXTENSIONS FOR JAVASCRIPT
▸ Futures and promises originated in functional programming and related
paradigms (such as logic programming) to decouple a value (a future) from
how it was computed (a promise), allowing the computation to be done
more flexibly, notably by parallelizing it.
WHERE DO PROMISES COME FROM?
13. REACTIVE EXTENSIONS FOR JAVASCRIPT
▸ A Promise is a proxy for a value not necessarily known when the promise is
created.
▸ It allows you to associate handlers with an asynchronous action's eventual
success value or failure reason.
▸ This lets asynchronous methods return values like synchronous methods:
instead of immediately returning the final value, the asynchronous method
returns a promise to supply the value at some point in the future.
PROMISES
14. REACTIVE EXTENSIONS FOR JAVASCRIPT
▸ Pending - initial state, neither fulfilled nor rejected.
▸ Fulfilled - the operation completed successfully.
▸ Rejected - the operation failed.
PROMISE STATES (STATE MACHINE)
15. REACTIVE EXTENSIONS FOR JAVASCRIPT
PROMISE EXAMPLE
const promise = new Promise(function (resolve, reject) {
setTimeout(function () {
const randomNumber = Math.floor(Math.random() * Math.floor(10));
if (randomNumber % 2 === 0) {
resolve('Success');
return;
}
reject('Error');
}, 300);
});
promise.then(console.log).catch(console.error);
Controlling the machine state
16. REACTIVE EXTENSIONS FOR JAVASCRIPT
PROMISE EXAMPLE (2)
Promise.resolve(10).then(x => x + 10).then(console.log);
21. REACTIVE EXTENSIONS FOR JAVASCRIPT
▸ Mathematical Abstractions - Helps us getting rid of details so we can look at
things a different way.
▸ Main Parts of Category Theory:
▸ Objects and Morphisms (functions) (which form a Category)
▸ Functors
▸ Natural Transformations
CATEGORY THEORY
22. REACTIVE EXTENSIONS FOR JAVASCRIPT
CATEGORIES
▸ A category consists of a collection of objects (just
abstractions) and morphisms (functions).
(X, Y, Z - objects)
▸ The morphisms must obey the following laws:
▸ They must me composable.
▸ Compositions must me associative.
▸ For each object a, there is an identity morphism.
24. REACTIVE EXTENSIONS FOR JAVASCRIPT
FUNCTORS
▸ A structure-preserving mapping between categories. (the return value is the same
type of functor)
▸ Let A and B be categories. A functor F from A to B is a mapping that:
▸ associates to each object a in A an object F(a) in B.
▸ associates to each morphism f in A a morphism F(f) in B such that the following two
conditions hold:
▸ F(ID(x)) = ID(F(X))
▸ F(g o f) = F(f) o F(g) for all morphisms f: x -> y, g: y -> z in A.
25. REACTIVE EXTENSIONS FOR JAVASCRIPT
CATEGORY THEORY OBJECTS IN JAVASCRIPT
const containerPrototype = {
map: function (fn) {
return Container(fn(this.value));
}
}
function Container(value) {
return Object.create(containerPrototype, { value: { value } });
}
console.log(Container(10).map(x => x + 100)); // > Container { value: 110 }
26. REACTIVE EXTENSIONS FOR JAVASCRIPT
CATEGORY THEORY OBJECTS IN JAVASCRIPT
Container(10).map(x => x + 100).map(x => '' + x); // > Container { value: '110' }
27. REACTIVE EXTENSIONS FOR JAVASCRIPT
CATEGORY THEORY OBJECTS IN JAVASCRIPT
[10].map(x => x + 100).map(x => '' + x);
28. REACTIVE EXTENSIONS FOR JAVASCRIPT
CATEGORY THEORY OBJECTS IN JAVASCRIPT
[10].map(x => x + 100).map(x => '' + x);
It’s a functor!
39. REACTIVE EXTENSIONS FOR JAVASCRIPT
PROMISE EXAMPLE (3)
Promise.resolve(10).then(x => x + 100).then(x => '' + x); // > Promise { value: '110' }
40. REACTIVE EXTENSIONS FOR JAVASCRIPT
PROMISE EXAMPLE (3)
Promise.resolve(10).then(x => x + 100).then(x => '' + x); // > Promise { value: '110' }
For values which are not promises, .then() acts like an asynchronous .map()
42. REACTIVE EXTENSIONS FOR JAVASCRIPT
PROMISE EXAMPLE (4)
Promise.resolve(10).then(x => Promise.resolve(x + 100)).then(x => '' + x);
// > Promise { value: '110' }
For values which are promises themselves, .then() acts like
the .flatMap() method from monads.
43. REACTIVE EXTENSIONS FOR JAVASCRIPT
PROMISE EXAMPLE (4)
Promise.resolve(10).then(x => Promise.resolve(x + 100)).then(x => '' + x);
// > Promise { value: '110' }
It’s flattening the structure! It’s not a functor!
44. REACTIVE EXTENSIONS FOR JAVASCRIPT
MONADS
▸ An extended functor.
▸ They flatten and map with context
49. MARBLE TESTING RXJS STREAMS
REACTIVE EXTENSIONS FOR JAVASCRIPT
▸ RxJS is a library for reactive programming using
Observables, to make it easier to compose
asynchronous or callback-based code.
50. REACTIVE EXTENSIONS FOR JAVASCRIPT
CREATING AN OBSERVABLE (THE OLD WAY)
import 'rxjs/add/observable/of';
import ‘rxjs/add/operator/map';
of(10).map(x => x + 100).map(x => '' + x).subscribe(console.log);
51. REACTIVE EXTENSIONS FOR JAVASCRIPT
CREATING AN OBSERVABLE
import { of } from ‘rxjs';
import { map } from ‘rxjs/operators';
of(10).pipe(map(x => x + 100), map(x => '' + x)).subscribe(console.log);
53. REACTIVE EXTENSIONS FOR JAVASCRIPT
CREATING AN OBSERVABLE
import { of } from ‘rxjs';
import { map } from ‘rxjs/operators';
of(of(10), of(10)).pipe(switchMap(x => x), map(x => x + 100)).subscribe(console.log);
58. REACTIVE EXTENSIONS FOR JAVASCRIPT
HOT AND COLD OBSERVABLES
▸ Cold - An observable is “cold” if its underlying producer is created and
activated during subscription.
▸ Hot - An observable is “hot” if its underlying producer is either created or
activated outside of subscription.
60. REACTIVE EXTENSIONS FOR JAVASCRIPT
COMMON THINGS THAT WE NEED
▸ debouncing
▸ cancelation
▸ retrying
▸ throttling
▸ timeouts
▸ detect only if something changed