Observables

What is an observable?

Let's start by comparing an Observable to a Promise.
A Promise is an eventual value.
An Observable is a stream of eventual values.
So an obervable is like a series of Promises.

Formally speaking:

An observable is a stream of 0 or more values.
The stream comes in over a period of time.
The stream is cancelable.

Use Cases for Observables

Working with APIs

  • Promises work great for the happy path
  • What if you want to retry a certain number of times?
  • What happens if you want to reload the data at some regular interval?
  • What happens if you want to iterate across a paginated API, but also show the data as it comes in?
    Observables can help you do all of that.

Coordinating multiple API requests

  • What if you have to coordinate multiple APIs in order to render a UI?
  • This can be complicated and error-prone.
    Observables help make this easy and relatively error-free.

Loading Indicators

Figuring out when to show a loading indicator can be hard

  • If an API request is taking too long, you should giver users some visual feedback
  • What if it's too fast? You don't want to immediately flash the indicator only to remove it a few milliseconds later.
    Observables can help conditionally render a loading indicator only if a pre-determined time interval has passed, such as 200ms for example.

Complex UI interactions like Dragging and Dropping

Observables help you manage adding and removing event listeners with ease.

  • Implementing a drag-and-drop interface can come with its own set of challenges.
  • You want to start listening to mouse movements when the user clicks on the elements
  • But you want to stop as soon as they release the mouse.
  • Other objects might care about where that object is, but only when it's moving.
    In this example, the other objects can be subscribed to the dragEventHandler and dropEventHandler of the object and will get notified when those events happen.
Show Comments