Background: RxJS & Observables
What We'll Cover
- (Very Brief) Conceptual Roots
- What is RxJS?
- What are observables?
- How are they used in Angular?
Don't let observables scare you away from Angular.
Functional and Reactive Programming (Really) Oversimplified
- Functional programming prefers:
- Immutability over state (data doesn't change)
- Results over steps
- Composition over structure (lots of pieces)
- Declarative over imperative style
- Reactive programming:
- Asynchronous and event-driven
- Think of an Excel spreadsheet
- But what kinds of events?
- A stream is a sequence of events over time
- Anything can be a stream, from mouse clicks to data from a server
Streams can then be thought of as arrays of values and operated on as such.
- For example, mouse click coordinates: [(100,200), (300,400), (110,350)]
Put it Together: Functional Reactive Programming (FRP)
- Around for 20+ years
- Entire applications can be built around streams
- Create or identify the streams in your application, then combine and subscribe to them
- Allows us to build in a declarative style by defining streams, how they are connected, and what happens as new values arrive over time
- With little to no application state (state is typically stored on certain streams or the DOM)
What are Observables?
- A data type introduced by RxJS to help us create, subscribe to, and react to streams
- Asynchronous, push-based sequences of data that can be subscribed to
- Think of them like an API for the stream, not the stream itself
|Single Return Value||Multiple Return Values|
|Object||Iterables (Array/Set/ Map)|
Common RxJS Operators
var source$ = Rx.Observable.range(1,4); //1,2,3,4 //map & flatMap: change each value source$.map(x => x*2); //2, 4, 6, 8 //filter: return only selected values based on custom logic source$.filter(x => x % 2 === 0); //2, 4 //reduce: do a computation on the stream and output final value source$.reduce((prev, curr) => prev + curr); //10 //scan: do a computation on the stream but output intermittment values source$.scan((prev, curr) => prev + curr); //1, 3, 6, 10 //take: take the first value source$.take(1) //1
RxJS in Angular
- Angular 2+ uses observables in two ways:
- Internally, to implement core logic like the EventEmitter
- In the API, specifically in forms and HTTP, to help data flow between components
- Practically, we use RxJS in three places:
- Services, where set up our REST calls
- Components, where we subscribe and use our data.
- Route resolvers, if we need data to load ahead of time.
We can still use promises.
(I'll show you how.)
Let's get started!
Background: RxJS & Observables in Angular
By Sam Julien