DEV Community

Cover image for Angular + RXJS Behavior Subject
Julie Gladden
Julie Gladden

Posted on • Updated on

Angular + RXJS Behavior Subject

Hey guys,

Today I want to walk you through how I use RXJS's Behavior Subject.

First of all, what is it and what can you do with it?

  1. It's an observable that you can use to store data and then emit that data everywhere that has subscribed to it.
  2. The data can be updated from any component, which then in turns updates all the subscribers.
  3. It has to have a starting value.
  4. You can subscribe to it at any time.
  5. You can unsubscribe from it at any time.

To figure this out, let's make a simple project that will allow us to share the name of a cat and subscribe to it.

First, create a service in your terminal.
ng g s cat-name

In cat-name.service.ts

/* This is our original source. If the value hasn't been otherwise
changed, this is the value you will get when you subscribe. */
nameSource = new BehaviorSubject<any>('Fluffy')

/* This takes our nameSource and turns it into an observable that
can be subscribed to. */
nameCurrent = this.nameSource.asObservable();

/* This is the function we will call that will allow us to update
the Cat's name. */
changeName$(name$) {$)

Enter fullscreen mode Exit fullscreen mode

Note** The $ after a variable just denotes that it is an observable. It doesn't effect the function of the variable at all.

Now, in our cat.ts file (or any TS file you are going to be using the Behavior Subject's value in, or updating the value in...)

//Variable to store the Behavior Subject observable in...

constructor(private nameService: CatNameService) {}

ngOnInit() {
  this.nameService.nameCurrent.subscribe(name$ => {
      this.catName = name$,
      //The logged name will be 'Fluffy'

//If I want to change the cat's name...
changeCatName() {
  //The logged name will be 'Stormy'
Enter fullscreen mode Exit fullscreen mode

After you call the 'changeName' function, since you are already subscribed, if you console.log 'this.catName', it will log as 'Stormy' instead of 'Fluffy'. Note that we did not implicitly change the catName variable. The changeName$ function emitted that value, and because we were already subscribed in our ngOnInit, we reassigned the variable in our subscription. Pretty cool, right?

Just remember, EVERYWHERE you are subscribed to 'nameCurrent' will update. EVERYWHERE.

Make sure to unsubscribe in places you don't want this to happen.

Like always, there's more that you can do with Behavior Subject, so make sure to check out their documentation to get the full picture. I wanted to make this one short and sweet, so if you have any questions ask down below!

Thanks for reading,

Top comments (0)