rxjs101 - what you need to know to get started with rxjs tomorrow

65

Upload: viliam-elischer

Post on 15-Apr-2017

240 views

Category:

Engineering


3 download

TRANSCRIPT

RxJS 101

$ whoami

Viliam ElischerSW Engineer at ZOOM International

github.com/vire

twitter.com/vireliam

What you need to know to get started withRxJS tomorrow

Java Scala Kotlin Clojure

JavaScriptC# C++ Swift

Ruby Python Groovy

The AsyncoGenesis

begin("In the beginning, God created the heavens and the earth", function(earth) ...)

Will there be light as rst callback param atthe end of the tunnel?

tunnel.end("...", function(light) ...)

No, there is just callback hell! findUser(userID, function(userErr, user) getProfile(user, function(profileErr ,profile) getFriends(profile, function(friendsErr, friends) // meh ); ); );;

Don't loose fate developers,I can see the Promised Land

getUserFromAPI(userID) .then(function(user) return getUserProfile(user); , ...) .then(function(userProfile) return getFriend(userProfile) , ...) .then(function(friends) // meh , .../*forever alone*/) .catch(function(reason) // The LORD will protect you from all evil! );

Promises look promising(+) are immutable (+) good at caching

despite some drawbacks(­) guaranteed future ­ no cancelation (­) single value (array of promisses)

What is RxJS

A Libraryfor composing asynchronousand event-based programs

using observable sequences

"Lodash for events."

"... any amount of events overany amount of time ..."

"Uses the same approach for browser andbackend."

Concepts

General theory of reactivity

Pull based Push based

localesFromLS() .filter(l => l != null) .map(l => l.toUpperCase()) .forEach(s => log(locale:$s))

localesFromAPI() .filter (s => s != null) .map(s => l.toUpperCase()) .subscribe(s => log(locale:$s))

Article: Duality of IEnumerable/IObservable

Iterable<T> and Iterator<T>

interactive computations where the consumersynchronously pulls data out from the producer

Observable<T> and Observer<T>

reactive computations where the producer asynchronouslypushes data to the consumer

Observableabstracts data source that accepts an observer and returnsa subscription

ties a producer to a consumeris by default lazy, and cold*provides a mechanism to unsubscribe / teardownfunction that takes an Observer

*Demystifying Cold and Hot Observables in RxJS

Observeris a consumer of events propagated by the Observable.next() method handles pushed values.error() method handles pushed errors.complete() method handles that the "stream is over"

Subjectis a special type (multicast) Observable

similar to EventEmitter - maintains subscribersdiffers from Observables which are by default unicastEvery Subject is an Observable - subscribeEvery Subject is an Observer - next, error, completeBehaviorSubject, ReplaySubject, and AsyncSubject.

Operatortransforms source stream into destination stream

joins subscriptionapplies a projection function, e.g map()returns an Observable that subscribes to the sourceObservable

Operator typesTransforming (map, debounce, delay)

Combining (merge, concat, switch)

Filtering (lter, nd)

Mathematical (sum, max, avg)

Boolean (every)

Conditional (amb)

Observable grammar

Grammar violations

Parametrized concurrencySchedulers

advanced topic, but in they responsible for time notion

RxJS= Observables + Operators + Schedulers

Disclaimer: RxJS is not FRPFRP is more than just set operations

(.map, .reduce, .lter)

What is it good for

User interactions -> DOM Events handling

NET -> Ajax, WebSockets

API -> Library gear

State Management -> NgRx, Redux-Rx

WebWorkers

Animations

Inspirationgithub.com/Reactive-Extensions/RxJS/tree/master/examples

How do I create an Observable?

Use of teardown logic

Observables have "purpose-based" staticmethods for creation

Observable.of()arguments to an observable sequence

Observable.from(iterable)(Array | Arguments | Iterable): An array-like or iterableobject to convert to an Observable sequence.

Observable.fromPromise

Observable.merge

Other creation methodsbindCallback, bindNodeCallback, ajax, webSocket + more

How do I use an operator?

.reduce() and .scan()

.map() and .mergeMap()

.switchMap()

.switchMap() in Angular 2 - out of the boxChristoph Burgdorf - Taking advantage of Observables in

Angular 2

@Component( selector: 'my­app', template: <div> <h2>Reddit Search</h2> <input type="text" [ngFormControl]="term"/> <ul> <li *ngFor="#item of items | async"><a href=item.url>item.title</a></li> </ul> </div> )export class App items: Observable<Array<string>>; term = new Control(); constructor(private redditService: RedditService) this.items = this.term.valueChanges .debounceTime(400)

Operators mastery at level 100

RxJS 5

Improvements:Compliance with the TC39 Observable SpecPerf -> operators are faster (removed closures)TypeScriptModularity -> bundling sizeMarbleTests

Migration notes

Contains RxJS

NgRx, Redux-Rx

Learning materials

Ofcial in-repo Documentaion

- interactive, written in Cycle.js

egghead.ioRxJS gitbookrxmarbles.com

Credits

Microsoft, Netix, Google

Erik Meijer & Matthew PodwysockiBen Lesh, André Staltz, OJ Kwon

Thank you

#devsUnitedgithub.com/vire

@vireliam