Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Scratching the Surface of RxJS

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)

Kevin Salter

September 28, 2016
Tweet

More Decks by Kevin Salter

Other Decks in Technology

Transcript

  1. 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
  2. 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:
  3. Reactive-Extensions/RxJS v 2.1.0 - 4.0 RxJS • invented at Microsoft

    around 2009 • open sourced in November of 2012 the early years…
  4. 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
  5. FRP

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

    and return a result while avoiding things like changing states and mutable data.
  7. 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?
  8. Terms • Observable (Core Type) • Observer, Schedulers, Subjects (Satellite

    Types) • Operators (inspired by Array#extras, i.e. map, filter, reduce)
  9. • DOM events • Animations • AJAX • WebSockets •

    Server Sent Events (SSE) • Alternative inputs (voice, joystick, etc.) Types of async in modern web applications
  10. • 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
  11. Cold Observables are “cold” by default. “Cold” observables create a

    new producer each time a consumer subscribes to them.
  12. 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.
  13. 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
  14. 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
  15. 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
  16. 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?
  17. 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
  18. 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 ++ +: :+
  19. at a high level, learning Rx reminds me of approaching

    learning git init clone commit push pull