Angular: Using BehaviorSubject to react to a user action

Recently I had a case where I needed some Angular components to listen to a user action and update their model based on that action.

That action was switching languages for specific components. There are many ways to actually achieve such a behavior, but I decided that the most elegant way was to use BehaviorSubject.

Subjects in Reactive Extensions (“rxjs/Rx”) are basically a special type of observables which you can subscribe and receive messages. Their dual native (being an observable and observer) allows them apart from just receiving, to send messages as well.

BehaviorSubject is a special type of Subject that has the following features

  • Expects an initial value
  • Adds a message into the subscription stream by using .next()
  • Upon subscription it returns the last message
  • You can read the last message without subscribing by using getValue()

Creating a BehaviorSubject :

Sending a message:

Subscribing:

Reading the value

:-)