Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
My learning about RxJS

Learning RxJS

Intro

  • Reactive programming is programming with asynchronous data streams, also deal with synchronous.

    • A stream is a sequence of ongoing events ordered in time, that can emit:
      • Value,
      • Error,
      • Completed signal
  • Everything could be considered as a stream: Single value, Array, Event, etc

  • ReactiveX combines

    • the Observer pattern with
    • the Iterator pattern and
    • functional programming with collections to managing sequences of events.
  • RxJS

    • Observable
    • Observer
    • Subject
    • Subscription
    • Operators
    • Scheduler

Other knowledge

Access array

  • forEach
  • map
  • filter
  • reduce
  • concat
  • flatten
Producer Consumer
Pull (function) Passive: produces data when requested. Active: decides when data is requested.
Push (DOM, events) Active: produces data at its own pace. Passive: reacts to received data.

Observable

Definition

  • is function, lazy computation
  • tie an Observer to a function/producer
  • deal ok with both async + sync
  • is unicast, each Observable is independent

Method

Creating

  • create <- Observer
  • from <- Array, Object like Array, Set
  • of <- values
  • interval <- number

Invoke / Dispose

  • subscribe() <-- { nextFn, errorFn, completeFn } aka Observer
  • unsubscribe() => Release resource or cancel Observable executions

Execute

  • next: zero to infinite
  • error, complete: once and not together

Hot and cold Observables

  • Cold Observable: if its producers is created AND activated during subscription (inside)
  • Hot Observable : if its producers is EITHER created OR activated OUTSIDE of subscription (outside)
  • You want a HOT observable when you don’t want to create your producer over and over again.
  • Warm Observable: ?

Observer

  • is consumer which consume data sent by Observable
  • is object: { nextFn, errorFn, completeFn }

Subscription

  • Result of Observable.subscribe(), has unsubscribe
  • Could has Subscription childs via add
  • if father unsubscribe, all childs follow.

Subject

Definition

  • is Observable, shaped like.
  • is Observer, duck-types as.
  • is multicast, with subscribe() that add Observers to internal observers list.
  • not reusable, after unsubscribed, completed or errored.

BehaviorSubject

  • is Subject
  • Represents a value that changes over time
  • Require initial value
  • Emit last (or initial) value to latest subscribed Observer
  • Observers subscribe after it's completed, only receive complete signal <-- no emitted value

ReplaySubject

  • is BehaviorSubject
  • Emit more values to last subscribed Observer than BehaviorSubject by setting:
    • number of values
    • time to last time value emitted
  • Observers subscribe after it's completed, receive all emitted values in buffer then complete signal

AsyncSubject

  • Last variant of Subject
  • Only emit last value to last subscribed Observers when it's completed
  • If not complete, emit nothing
  • Observers subscribe after it's completed, still receive last emitted value

Operators

Definition

  • are pure functions
  • create new Observable base on current Observable
  • 2 type
    • Static : pure functions, attached to the Observable class, used to create Observables from scratch.
    • Instance: functions, attached with specific instance of Observable class - through this

Groups

Start with these

  • map
  • filter
  • scan
  • mergeMap
  • switchMap
  • combineLatest
  • concat
  • do

Creation Operators : operators that create Observable:

  • from, of
  • throw, empty, never
  • create, interval, timer
  • fromEventPattern, fromEvent, fromPromise
  • repeat, repeatWhen

Transformation Operators: transform Observable value with callback

  • map, mapTo, mergeMap, mergeMapTo, concatMap, switchMap
  • scan,
  • buffer, bufferTime

Filtering Operators: filter emit value that pass condition

  • filter
  • take, takeUntil, takeWhile,
  • skip, skipUntil, skipWhile,
  • first, last,
  • throttleTime, debounceTime,
  • distinctUntilChanged

Combination Operators: combine Observables

  • merge, mergeAll, concat
  • startWith
  • combineLatest, withLatestFrom
  • forkJoin
  • zip

Error handling Operators

  • catch
  • retry, retryWhen

Utility Operators

  • do: do something without causing side-effect to original value
  • delay
  • toPromise

Multicast Operators

  • share
  • multicast
  • publish

Conditional and Boolean Operators

  • defaultIfEmpty
  • every
  • isEmpty

Mathematical and Aggregate Operators

  • count
  • max/min
  • reduce

Operators of Higher Order Observables:

HOO is Observable that returns Observable, e.g multid array. Often use:

  • mergeMap (flatMap): multi stream concurrently
  • concatMap: 1 stream per time, streaming sequentially
  • switchMap: 1 stream per time, drop current stream if other is coming
  • exhaustMap: 1 stream per time, ignore next streams if one is streaming (opposite to switchMap)

Scheduler

  • A scheduler controls when a subscription starts and when notifications are delivered.
    • data structure
    • execution context: immediately or callback
    • virtual clock
  • Methods:
    • queue: During same job but on a queue - "breadth first"
    • asap: Next job - "microtask"
    • async: Next timeout
    • animationFrame: Next requestAnimationFrame
  • PS: Hard to understand, not very familiar with me

Notes

  • A Promise is simply an Observable with one single emitted value

QA

  • HTTP request complete observable the nao? <-- Like of, return an object
  • unicast vs multicast
  • AsyncSubject
  • pure function ?
  • Combination Operators
  • use case for higher-order observables' operators

Excercies

  • Sample Observable
  • Sample Observer
  • Sample Subject, BehaviorSubject, ReplySubject, AsyncSubject
  • Sample popular operators

Homework

  • Implementing a "Who to follow" suggestions box
    In Twitter there is this UI element that suggests other accounts you could follow:

    We are going to focus on imitating its core features, which are:

    On startup, load accounts data from the API and display 3 suggestions
    On clicking "Refresh", load 3 other account suggestions into the 3 rows
    On click 'x' button on an account row, clear only that current account and display another
    Each row displays the account's avatar and links to their page
    We can leave out the other features and buttons because they are minor. And, instead of Twitter, which recently closed its API to the unauthorized public, let's build that UI for following people on Github. There's a [Github API](https://developer.github.com/v3/users/#get-all-users) for getting users.

    The complete code for this is ready at http://jsfiddle.net/staltz/8jFJH/48/ in case you want to take a peak already.

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.