The document discusses functional reactive programming (FRP) in JavaScript, detailing its concepts, advantages, and practical applications. It covers functional programming principles, reactive programming fundamentals, and how to create and utilize observables in different scenarios like autocomplete and drag-and-drop. Additionally, it mentions popular libraries like RxJS and educational resources for learning FRP.
F + R+ P
■ Powerful composition and aggregation of
streams
■ Good fit for concurrent and event-driven
systems
■ Declarative
■ Easy to test
[6]
19
20.
Observables
■ Streamof data over time
■ Hot vs cold observables
■ Asynchronous
■ Lazy
■ queryable, bufferable, pausable…
■ more than 120 operations
[7]
20
Autocomplete 2/2
.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 }
);
28
29.
Drag & Drop1/2
var mousedown = Rx.Observable.fromEvent(dragTarget, 'mousedown');
var mousemove = Rx.Observable.fromEvent(document, 'mousemove');
var mouseup = Rx.Observable.fromEvent(dragTarget, 'mouseup');
[11]
29
30.
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
31.
Some Cool Stuffon 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
Conclusion
■ Thereis a learning curve
■ Great abstraction for async & events
■ Improves
● Readability
● Reusability
● Scalability
■ Both on the front- and backend
36
37.
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
#8 Bevor functional reactive programming -> functional
Im Gegensatz zu imperativ wird mit mathematischen funktionen gearbeitet.
Instruktionen
Mapping Input -> Output immer gleich unabhängig vom ausführungszeitpunkt
Immutable