Scratching the Surface of RxJS

C3a44402b29aebcf9f28ae9242545ae7?s=47 Kevin Salter
September 28, 2016

Scratching the Surface of RxJS

This deck was presented at 7Geese HQ in Gastown (7Geese.com) during Vancouver Startup Week (http://sched.co/82Tj). It gives a general introduction to RxJS as I share my experience learning the library and programming style. You can also watch it on Periscope http://bit.ly/2de0kM9 (Part 1) and http://bit.ly/2cRDneS (Part 2)

C3a44402b29aebcf9f28ae9242545ae7?s=128

Kevin Salter

September 28, 2016
Tweet

Transcript

  1. @KevinSalter

  2. ReactiveX

  3. just scratching the surface of ReactiveX and RxJS

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

  5. 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
  6. TIL r/mildlyinteresting/

  7. So, what is ReactiveX?

  8. ReactiveX is a library for composing asynchronous and event-based programs

    by using observable sequences.
  9. 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:
  10. Reactive-Extensions/RxJS v 2.1.0 - 4.0 RxJS • invented at Microsoft

    around 2009 • open sourced in November of 2012 the early years…
  11. 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
  12. RxJS v 5.0.0-beta.12

  13. RxJS Contributors

  14. What is Reactive Programming?

  15. None
  16. FRP

  17. Functional Reactive Programming

  18. Functional programming typically involves declaratively composing functions to process data

    and return a result while avoiding things like changing states and mutable data.
  19. Reactive programming is programming with asynchronous data streams.

  20. A data stream is a collection of data over time

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

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

  23. None
  24. None
  25. None
  26. None
  27. None
  28. None
  29. Observables can model both synchronous and asynchronous data

  30. None
  31. None
  32. Marble Diagrams

  33. Anatomy of a Marble Diagram

  34. Anatomy of a Marble Diagram

  35. Anatomy of a Marble Diagram

  36. Anatomy of a Marble Diagram

  37. http:/ /rxmarbles.com

  38. None
  39. None
  40. None
  41. 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?
  42. what is RxJS?

  43. “RxJs is LoDash or Underscore for async”

  44. Terms • Observable (Core Type) • Observer, Schedulers, Subjects (Satellite

    Types) • Operators (inspired by Array#extras, i.e. map, filter, reduce)
  45. Rx.Observable

  46. None
  47. None
  48. code examples https://jsbin.com/xamobok/60/edit?js,console

  49. None
  50. Observables are lazy Push collections of multiple values.

  51. None
  52. None
  53. None
  54. speaking of promises…

  55. • DOM events • Animations • AJAX • WebSockets •

    Server Sent Events (SSE) • Alternative inputs (voice, joystick, etc.) Types of async in modern web applications
  56. • 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
  57. None
  58. Observables come in 2 temperatures

  59. Hot Cold

  60. Cold Observables are “cold” by default. “Cold” observables create a

    new producer each time a consumer subscribes to them.
  61. None
  62. None
  63. 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.
  64. Cold Observables are like recorded video Hot Observables are like

    live video
  65. None
  66. None
  67. None
  68. cold / hot example https://jsbin.com/seduni/16/edit?js,console

  69. more about operators…

  70. “RxJs is like LoDash for asynchronous data streams”

  71. methods that perform calculations on values Operators

  72. None
  73. 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
  74. 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
  75. 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
  76. 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?
  77. 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
  78. 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 ++ +: :+
  79. at a high level, learning Rx reminds me of approaching

    learning git init clone commit push pull
  80. None
  81. Quick, to the decision tree of Observable Operators!!!

  82. None
  83. examples

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

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

  86. ok, what next? cycle.js redux-observable

  87. The End