Angular 6 - Observable explanation in plain English

For a laugh, this fictional story only for dummies like me to understand:

After 7 years of marriage, wonderful John still in love with beautiful Kate, but Kate's girlfriends all tell her to keep an eye on John who works longer and longer hours now in the office.

"I'll call you back, busy, work on it." So CALLBACK is what Kate always hears when she calls John, one call-out one call-back. Though sometimes not easy to keep track of things for John.

John loves Kate, he upgrades the wording and handling by saying "I PROMISE (to do call Kate back)!" THEN again Kate is pleased and she establishes a safenet to CATCH the unexpected response, a better way to organize than Callbacks.

Kate is very happy with John, but her girlfriends still gossip on it, especially technology is advancing. So they all tell Kate, "you'd better OBSERVE him..." John is now OBSERVABLE to Kate who jokes to her darling that she's SUBSCRIBE to him, meaning John can now response continuously, no longer once, and can be multiple times, response can be streamed! Yulp, instead of one response per request, he sets up a little camera on his desk to keep her updated all the time. For example, Kate cares about his diet, he'd report "honey I just had a piece of cheese cake and an apple for breakfast", ... "honey I had a yummy lunch from ..." Lovely!

The END


It's like an event, by subscribing you are saying "let me know when this happens..".. so let's say you do a http request, you dont really know how long it will take, so the observable is just a placeholder or event you can subscribe to, which says when this happens, do something. That is, When this http request comes back, whenever that happens to be, read the value. The function you subscribe with will be run when it comes back.


Lets start with promises

In Javascript, Promises are a common pattern used to handle async code elegantly. If you don't know what promises are, start there. They look something like this:

todoService.getTodos() // this could be any async workload
.then(todos => {
  // got returned todos
})
.catch(err => {
  // error happened
})

The important parts:

todoService.getTodos() // returns a Promise

Lets forget about how getTodos() works for now. The important thing to know is that lots of libraries support Promises and can return promises for async workloads like http requests.

A Promise object implements two main methods that make it easy to handle the results of the async work. These methods are .then() and .catch(). then handles "successful" results and catch is an error handler. When the then handler returns data, this is called resolving a promise, and when it throws an error to the catch handler, this is called rejecting.

.then(todos => { // promise resolved with successful results })
.catch(err => { // promise rejected with an error }) 

The cool thing is, then and catch also return promises so you can chain them like this:

.then(todos => {
  return todos[0]; // get first todo
})
.then(firstTodo => {
  // got first todo!
})

Here's the catch: Promises can only resolve OR reject ONCE

This works out alright for things like http requests because http requests are fundamentally execute once and return once (success or error).

What happens when you want an elegant way to stream async data? Think video, audio, real-time leaderboard data, chat room messages. It would be great to be able to use promises to set up a handler that keeps accepting data as it streams in:

// impossible because promises only fire once!
videoService.streamVideo()
.then(videoChunk => { // new streaming chunk })

Welcome to the reactive pattern

In a nutshell: Promises are to async single requests, what Observables are to async streaming data.

It looks something like this:

videoService.getVideoStream() // returns observable, not promise
.subscribe(chunk => {  // subscribe to an observable
   // new chunk
}, err => {
  // error thrown
});

Looks similar to the promise pattern right? One major difference between observables and promises. Observables keep "emitting" data into the "subscription" instead of using single use .then() and .catch() handlers.

Angular's http client library returns observables by default even though you might think http fits the single use promise pattern better. But the cool thing about reactive programming (like rxJS) is that you can make observables out of other things like click events, or any arbitrary stream of events. You can then compose these streams together to do some pretty cool stuff.

For example, if you want to refresh some data every time a refresh button gets clicked AND every 60 seconds, you could set up something like this:

const refreshObservable = someService.refreshButtonClicked(); // observable for every time the refresh button gets clicked
const timerObservable = someService.secondsTimer(60); // observable to fire every 60 seconds

merge(
  refreshObservable,
  timerObservable
)
.pipe(
  refreshData()
)
.subscribe(data => // will keep firing with updated data! )

A pretty elegant way to handle a complex process! Reactive programming is a pretty big topic but this is a pretty good tool to try and visualize all the useful ways you can use observables to compose cool stuff.

note: this is untested pseudocode written for illustration purposes only