Reactive Programming in Angular

Learn how to enable reactive programming for handling asynchronous data streams and implement a key-logger component using RxJS to illustrate observable usage, emphasizing fromEvent for creating observables from DOM events.

We learned how to create observables and return a stream of events. That’s not all, however. This stream can combine many operations before hitting observers subscribed to it. Just as we can manipulate arrays with methods such as map or filter to transform them, we can do the same with the stream of events emitted by observables. It is a pattern known as reactive programming, and Angular makes the most of this paradigm to handle asynchronous information.

Observer pattern: Core of reactive programming

The observer pattern stands at the core of what we know as reactive programming. The most basic implementation of a reactive script encompasses several concepts that we need to be familiar with:

  • An observable

  • An observer

  • A timeline

  • A stream of events

  • A set of composable operators

Sound daunting? It isn’t. The big challenge here is to change our mindset and learn to think reactively, which is the primary goal of this section.

Note: Reactive programming entails applying asynchronous subscriptions and transformations to observable streams of events.

Let’s explain it through a more descriptive example. Think about an interaction device such as a keyboard. It has keys that the user presses. Each one of those keystrokes triggers a specific keyboard event, such as keyup. The keyup event features a wide range of metadata, including—but not limited to—the numeric code of the specific key the user pressed at a given moment. As the user continues hitting keys, more keyup events are triggered and piped through an imaginary timeline that should look like the following diagram:

Get hands-on with 1200+ tech skills courses.