Functional Reactive Programming with RxJS

Alex Jover

  • FullStack JS dev
  • Mentor at DevMeetings
  • Community and OSS contributor
  • From Agost

What is FRP?

FP + RP

What is Reactive Programming?

Programming with asynchronous observables data streams
André Staltz, Reactive programming introduction

ReactiveX

http://reactivex.io

  • Reactive spec
  • For most of languages
  • RxJS

A stream is composed by:

  • Observables
  • Operators
  • Subscription

Let the show begin!

Understanding a stream


						Observable.from([1,2,3])
							.map(num => num + 1)
							.filter(num => num % 2)
							.subscribe(num => console.log(num))
					

Immutability, in/out, testeability

More, more, more!


						const obs = Observable.from([1,2,3])
							.map(num => num + 1)
							.filter(num => num % 2)

						obs.subscribe(num => console.log("From 1", num))
						obs.subscribe(num => console.log("From 2", num))
					

One stream, multiple subscriptions

Third round!


						const obs1 = Observable.from([1,2,3])
						const obs2 = Observable.from([4,5,6])

						Observable.merge(obs1, obs2)
							.subscribe(num => console.log(num))
					

Multiple streams composition

I'm getting addicted!


						const items$ = Rx.Observable.from([1,2,3,4,5])
							.partition((x) => x % 2 == 0)

						const evens = items$[0]
						const odds = items$[1]

						evens.subscribe(data =>	console.log(`even ${data}`))
						odds.subscribe(data => console.log(`odd ${data}`))
					

Streams separation

Operators: 9 categories, ~120 in total

  • Creation
  • Transformation
  • Filtering
  • Combination
  • Multicasting
  • Error Handling
  • Utility
  • Conditional and Boolean
  • Mathematical and Aggregate

Most used


					Observable
						.from // Promise, array or iterable
						.fromEvent // DOM event, NodeJS EventEmmiter
						.of
						.bindCallback
						.bindNodeCallback

						.map/.mapTo
						.mergeMap
						.switchMap

						.filter
						.first/.last
						.take

						.merge
						.combineLatest
						.concat
						.zip
						.forkJoin
					

Real examples

Typeahead in Angular 2


						const obs1 = Observable.fromEvent(input, 'keyup')
							.map(e => e.target.value)
							.filter(value => value.length > 2) // min 3 characters
							.distinctUntilChanged()
							.debounceTime(500) // ms
							.mergeMap(word => this.http.get('...'))
							.retry(2)
							.subscribe(res => console.log(res))
					

Double click


						const click$ = Rx.Observable.fromEvent(document, 'click')

						click$.bufferWhen(() => click$.delay(350))
							.map(clicks => clicks.length)
							.filter(clicks => clicks > 1)
							.subscribe(clicks => console.log(clicks))
					

How would you do a drag event?

Resources

Links

Workshop Angular 2 y Redux

Suscribete! goo.gl/rPdx4f


Thanks

mood