Rxjs
A Better Way to Learn RxJS & Observables

Using BehaviorSubject for Values That Change over Time

PRO

There are a few different types of subjects in RxJS, but the most common one that pops up when building real world applications is the BehaviorSubject.

Lets say we want to store what a user's name is, but we also want them to be able to change it. We'd want to store an initial name, have the ability to update it, and also be able to access whatever the current name is set to at any given time.

This is precisely what BehaviorSubject allows you to do. Lets see how this example use case would actually work:

Instantiate a new BehaviorSubject with an initial value

In this example, the initial value will be a string (Eric)

let currentNameSubject = new BehaviorSubject('Eric');

To get the current value, invoke the getValue method:

currentNameSubject.getValue();
// => 'Eric'

To change the value of an existing BehaviorSubject, call the next method with a new value:

currentNameSubject.next('Obama');

And if we were to call getValue again:

currentNameSubject.getValue();
// => 'Obama'

Subscribing to value changes

The whole point of using RxJS is to asynchronously update & share data across your application. This is done by subscribing to the Observable instead of calling getValue synchronously:

let currentNameSubject = new BehaviorSubject('Eric');

currentNameSubject.subscribe((val) => {
    console.log(val);
})
// => 'Eric'

currentNameSubject.next('Obama');
// => 'Obama'

currentNameSubject.next('Jacob');
// => 'Jacob'

Real world example

In the video above we demonstrated how you can use a BehaviorSubject for storing & sharing data within an Angular Service, and then injecting it into other services and components. Below is the live demo of the running code:

 

I finished! On to the next chapter