Behavior Subject and Rxjs

Helmi Bejaoui
2 min readMay 26, 2021

--

If you are wandering what is Behavior Subject and its case usage you are in the right place but first we need to explain it all in a simple sequence

Always start with asking simple question and that will lead to the right answer

What is a Behavior Subject?

A behavior Subject is a type of Subject

What is a Subject then?

A Subject is a special type of Observable so basically you can subscribe to messages like any other observable, An Observable is basically a function that can return a stream of values to an observer over time, this can either be synchronously or asynchronously. The data values returned can go to an infinite range of values.

Now, after we have answered our questions , we need to start with must know Observable information

Observable lifecycle

With some help from observers and subscriptions the Observable instance passes through these four stages throughout its lifetime:

  • Creation
  • Subscription
  • Execution
  • Destruction

Behavior Subject added values

  • It needs an initial value as it must always return a value on subscription even if it hasn’t received a next()
  • Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an on next
  • At any point, you can retrieve the last value of the Subject in a non-observable code using the getValue() method.

Unique features of a subject compared to an observable are:

  • It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.

In addition, you can get an observable from behavior subject using the asObservable() method on BehaviorSubject.

Usage Case in Vue js

To demonstrate a Behavior Subject usage will be taking a Vue js example where we want to have access to a certain value in all of our components.

We start by creating the file that contains our Behavior Subject and its methods

import {BehaviorSubject} from 'rxjs';

const config = new BehaviorSubject(null);

export const ConfigState = {
setConfig: (message) => config.next({config: message}),
clearConfig: () => config.next(null),
getConfig: () => config.asObservable()
};

In our main vue instance we can do the following

import Vue from 'vue';
import axios from "axios";
import {ConfigState} from "./state/ConfigState";
new Vue({
el: '#app',
methods: {
fillConfig() {
axios.get('/api/configuration/')
.then(response => {
ConfigState.setConfig(response.data);
})
},
},
mounted() {
this.fillConfig();
},
template: '<App/>',
components: {
App
}
})

By adding launching fillConfig methods in our main instance, anywhere in the app we will be able to retrieve config last value through subscribing.

mounted() {
this.subscription = ConfigState.getConfig().subscribe(config => {
if (config) {
console.log(config);
}
});

},

And never forget to unsubscribe when you component is a bout to get destroyed as it prevent memory leaks

beforeDestroy () {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}

Happy coding!!

--

--

No responses yet