Slide 1

Slide 1 text

@KevinSalter

Slide 2

Slide 2 text

ReactiveX

Slide 3

Slide 3 text

just scratching the surface of ReactiveX and RxJS

Slide 4

Slide 4 text

`whoami` Front-End Developer | 7Geese @KevinSalter Kevin Salter

Slide 5

Slide 5 text

road map 1. What is ReactiveX and RxJS? 2. Why would I want to learn and use it? 3. How does it work? key points

Slide 6

Slide 6 text

TIL r/mildlyinteresting/

Slide 7

Slide 7 text

So, what is ReactiveX?

Slide 8

Slide 8 text

ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences.

Slide 9

Slide 9 text

ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences. • RxJava • RxJS • Rx.PY • RxClojure • RxSwift • and more… • RxScala • Rx.rb • rx.NET Different flavours:

Slide 10

Slide 10 text

Reactive-Extensions/RxJS v 2.1.0 - 4.0 RxJS • invented at Microsoft around 2009 • open sourced in November of 2012 the early years…

Slide 11

Slide 11 text

ReactiveX/rxjs v 5.0.0-beta.12 RxJS 5.0 is internally simpler, (4.3x average) faster, and designed to be aligned with the TC39 proposal for Observables as of Sept. 9th, 2016

Slide 12

Slide 12 text

RxJS v 5.0.0-beta.12

Slide 13

Slide 13 text

RxJS Contributors

Slide 14

Slide 14 text

What is Reactive Programming?

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

FRP

Slide 17

Slide 17 text

Functional Reactive Programming

Slide 18

Slide 18 text

Functional programming typically involves declaratively composing functions to process data and return a result while avoiding things like changing states and mutable data.

Slide 19

Slide 19 text

Reactive programming is programming with asynchronous data streams.

Slide 20

Slide 20 text

A data stream is a collection of data over time

Slide 21

Slide 21 text

You can also think of data streams as a never-ending array

Slide 22

Slide 22 text

static array vs stream https://jsbin.com/telofe/29/edit?js,console

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

Observables can model both synchronous and asynchronous data

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

Marble Diagrams

Slide 33

Slide 33 text

Anatomy of a Marble Diagram

Slide 34

Slide 34 text

Anatomy of a Marble Diagram

Slide 35

Slide 35 text

Anatomy of a Marble Diagram

Slide 36

Slide 36 text

Anatomy of a Marble Diagram

Slide 37

Slide 37 text

http:/ /rxmarbles.com

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

1. not mutating any data, just returning new streams 2. no need to maintain state, i.e. a counter, or building up an array 3. also, notice there are no control flow statements (i.e. if, else) 4. no need to set/clear setTimeouts or setIntervals 5. specify the dynamic behaviour of a value completely at the time of declaration 6. (ideally) more terse, cleaner, more maintainable code What’s the advantage over event listeners, or an imperative programming style, for example?

Slide 42

Slide 42 text

what is RxJS?

Slide 43

Slide 43 text

“RxJs is LoDash or Underscore for async”

Slide 44

Slide 44 text

Terms • Observable (Core Type) • Observer, Schedulers, Subjects (Satellite Types) • Operators (inspired by Array#extras, i.e. map, filter, reduce)

Slide 45

Slide 45 text

Rx.Observable

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

code examples https://jsbin.com/xamobok/60/edit?js,console

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

Observables are lazy Push collections of multiple values.

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

speaking of promises…

Slide 55

Slide 55 text

• DOM events • Animations • AJAX • WebSockets • Server Sent Events (SSE) • Alternative inputs (voice, joystick, etc.) Types of async in modern web applications

Slide 56

Slide 56 text

• DOM events (0-n values) • Animations (cancellable) • AJAX (1 value) • WebSockets (0-n values) • SSE (0-n values) • Alternative inputs (0-n values) Promises only really make sense for one of these

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

Observables come in 2 temperatures

Slide 59

Slide 59 text

Hot Cold

Slide 60

Slide 60 text

Cold Observables are “cold” by default. “Cold” observables create a new producer each time a consumer subscribes to them.

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

Hot Hot observables share a single producer with every consumer that subscribes to them. Hot observables are "live" sequences, meaning that they are happening whether we observe them or not.

Slide 64

Slide 64 text

Cold Observables are like recorded video Hot Observables are like live video

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

cold / hot example https://jsbin.com/seduni/16/edit?js,console

Slide 69

Slide 69 text

more about operators…

Slide 70

Slide 70 text

“RxJs is like LoDash for asynchronous data streams”

Slide 71

Slide 71 text

methods that perform calculations on values Operators

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

Types of Operators • Transformation map, scan, switchMap, • Combination combineLatest, concat, merge, startWith • Creation from, fromPromise, of • Filtering debounceTime, distinctUntilChanged, take, takeUntil • Multicasting share, publish • Error Handling catch, retry, retryWhen • Utility do, let, delay

Slide 74

Slide 74 text

Aggregate All Amb and_ And Any apply as_blocking AsObservable AssertEqual asyncAction asyncFunc Average averageDouble averageFloat averageInteger averageLong blocking Buffer bufferWithCount bufferWithTime bufferWithTimeOrCount byLine cache case Cast Catch catchException collect collect CombineLatest combineLatestWith Concat concat_all concatMap concatMapObserver concatAll concatWith CombineLatest combineLatestWith Concat concat_all concatMap concatMapObserver concatAll concatWith Connect connect_forever cons Contains controlled Count countLong Create cycle Debounce decode DefaultIfEmpty Defer deferFuture Delay delaySubscription delayWithSelector Dematerialize Distinct DistinctUntilChanged Do doAction doOnCompleted doOnEach doOnError doOnRequest doOnSubscribe doOnTerminate doOnUnsubscribe doseq doWhile drop dropRight dropUntil dropWhile ElementAt ElementAtOrDefault Empty empty? encode ensures error every exclusive exists expand failWith Filter filterNot

Slide 75

Slide 75 text

Finally finallyAction finallyDo find findIndex First FirstOrDefault firstOrElse FlatMap flatMapFirst flatMapIterable flatMapIterableWith flatMapLatest flatMapObserver flatMapWith flatMapWithMaxConcurrent flat_map_with_index flatten flattenDelayError foldl foldLeft for forall ForEach forEachFuture forIn forkJoin From fromAction fromArray FromAsyncPattern fromCallable fromCallback FromEvent FromEventPattern fromFunc0 from_future from_iterable from_list fromNodeCallback fromPromise fromRunnable Generate generateWithAbsoluteTime generateWithRelativeTime generator GetEnumerator getIterator GroupBy GroupByUntil GroupJoin head headOption headOrElse if ifThen IgnoreElements indexOf interleave interpose Interval into isEmpty items Join join (string) jortSort jortSortUntil Just keep keep-indexed Last lastOption LastOrDefault lastOrElse Latest Latest length let letBind limit LongCount ManySelect Map MapCat map-indexed map_with_index Materialize Max MaxBy Merge mergeAll merge_concurre mergeDelayErro mergeObservab

Slide 76

Slide 76 text

mergeWith Min MinBy MostRecent Multicast nest Never Next none nonEmpty nth ObserveOn ObserveOnDispatcher observeSingleOn of of_array ofArrayChanges of_enumerable of_enumerator ofObjectChanges OfType ofWithScheduler onBackpressureBlock onBackpressureBuffer onBackpressureDrop OnErrorResumeNext onErrorReturn onExceptionResumeNext orElse pairs pairwise partition partition-all pausable pausableBuffered pluck product Publish PublishLast publish_synchronized publishValue raise_error Range Reduce reductions RefCount Repeat repeat_infinitely repeatWhen Replay rescue_error rest Retry retry_infinitely retryWhen Return returnElement returnValue runAsync Sample Scan scope Select (alternate name of Map) select (alternate name of Filter) selectConcat selectConcatObserver SelectMany selectManyObserver select_switch selectSwitch selectSwitchFirst selectWithMaxConcurrent select_with_index seq SequenceEqual sequence_eql?

Slide 77

Slide 77 text

SequenceEqualWith Serialize share shareReplay shareValue Single SingleOrDefault singleOption singleOrElse size Skip SkipLast skipLastWithTime SkipUntil skipUntilWithTime SkipWhile skip_while_with_index skip_with_time slice sliding slidingBuffer some sort sort-by sorted-list-by split split-with Start startAsync startFuture StartWith stringConcat stopAndWait subscribe SubscribeOn SubscribeOnDispatcher subscribeOnCompleted subscribeOnError subscribeOnNext Sum sumDouble sumFloat sumInteger sumLong Switch switchCase switchIfEmpty switchLatest switchMap switchOnNext Synchronize Take take_with_time takeFirst TakeLast takeLastBuffer takeLastBufferWithTime takeLastWithTime takeRight (see also: TakeLast) TakeUntil takeUntilWithTime TakeWhile take_while_with_index tail tap tapOnCompleted tapOnError tapOnNext Then thenDo Throttle throttleFirst throttleLast throttleWithSelector throttleWithTimeout Throw

Slide 78

Slide 78 text

throwError throwException TimeInterval Timeout timeoutWithSelector Timer Timestamp To to_a ToArray ToAsync toBlocking toBuffer to_dict ToDictionary ToEnumerable ToEvent ToEventPattern ToFuture to_h toIndexedSeq toIterable toIterator ToList ToLookup toMap toMultiMap ToObservable toSet toSortedList toStream ToTask toTraversable toVector tumbling tumblingBuffer unsubscribeOn Using When Where while whileDo Window windowWithCount windowWithTime windowWithTimeOrCount windowed withFilter withLatestFrom Zip zipArray zipWith zipWithIndex ++ +: :+

Slide 79

Slide 79 text

at a high level, learning Rx reminds me of approaching learning git init clone commit push pull

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

Quick, to the decision tree of Observable Operators!!!

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

examples

Slide 84

Slide 84 text

search / autocomplete https://jsbin.com/nicobo/41/edit?js,output

Slide 85

Slide 85 text

drag and drop https://jsbin.com/kegeje/18/edit?js,output

Slide 86

Slide 86 text

ok, what next? cycle.js redux-observable

Slide 87

Slide 87 text

The End