Key Tools for Reactive Programming in Angular by RxJS Observables

GuruPrakash August 24, 2024
key-tools-for-reactive-programming-in-angular-by-rxjs-observables

Subject, BehaviorSubject, and ReplaySubject are specific forms of observables in Angular RxJS that are unique and extendable and can also be leveraged for the purpose of pushing new data within the observable stream.

What is BehaviorSubject?

BehaviorSubject acts like an in-memory store for the last piece of data. When someone wants to listen, they immediately get this stored data. We can also check what the current value is by using new BehaviorSubject('helloDevstoc').getValue().

When to use BehaviorSubject?

I find BehaviorSubject useful for getting the current data and setting the initial value. However, if you start with null, new listeners will get null. To avoid this, try using ReplaySubject or a filter.

BehaviorSubject Example:

import { BehaviorSubject, Observable } from 'rxjs';

// Create a BehaviorSubject with an initial value
const subject = new BehaviorSubject('Initial value');

// Subscribe to the BehaviorSubject
subject.subscribe((value) => {
  console.log('New value:', value);
});

// Emit new values to the BehaviorSubject
subject.next('Value 1');
subject.next('Value 2');

//OUTPUT 
New value: Initial value
New value: Value 1
New value: Value 2

We imported BehaviorSubject and Observable from the rxjs library. We created a BehaviorSubject with an initial value of 'Initial value'. We subscribed to the BehaviorSubject using the subscribe method. Whenever a new value is emitted, the callback function will run. We emitted new values to the BehaviorSubject using the next method; these new values will be received by the subscribers.

As you can see, the BehaviorSubject emitted the initial value and then the subsequent values that were emitted using next. The new subscribers will also immediately receive the latest value upon subscribing.
This is a simple example of how BehaviorSubject works in Angular. You can modify the code to suit your own needs, using different initial values, emitting different types of values, and using all of the RxJS operator functionality on the BehaviorSubject.

What is ReplaySubject?

ReplaySubject stores the last few values, and BehaviorSubject stores the last value only.

When to use ReplaySubject?

ReplaySubject is similar to BehaviorSubject, except it does not have a starting value. So if a listener is attached, the value will be `undefined` until a value is emitted. You would use ReplaySubject so you can keep track of the last few values emitted from an Observable, but again, do not be surprised that you can't access the current value; only listen for it.

ReplaySubject Example:

import { ReplaySubject } from 'rxjs';

// Create a ReplaySubject with a buffer size of 2
const subject = new ReplaySubject(2);

// Emit values to the ReplaySubject
subject.next('Value 1');
subject.next('Value 2');
subject.next('Value 3');

// Subscribe to the ReplaySubject
subject.subscribe((value) => {
  console.log('New value:', value);
});

// Emit another value
subject.next('Value 4');

//OUTPUT
New value: Value 2
New value: Value 3
New value: Value 4

We are importing ReplaySubject from the rxjs library. As you can see in the above example, we create a ReplaySubject with a buffer size of 2, meaning it is going to store the last 2 emitted values. In the example, we emit 4 values to the ReplaySubject using the next method. Then we subscribe to the ReplaySubject using the subscribe method. When we subscribe to the ReplaySubject, it is going to emit the last 2 values stored in its buffer to the subscriber.

As you can see, when the subscriber subscribes to the ReplaySubject, they immediately receive the last 2 emitted values to the ReplaySubject, and then they will receive the subsequently emitted values. This is the behavior of a ReplaySubject with a buffer size of 2.

What is Subject?

A Subject would not store the values sent to it but rather would be a recipient for any future messages sent after the listener is created.

When to use Subject?

Subject is useful when you just care about what is happening at the present moment, when components are talking to each other, or when something occurs like a click on a button, and you do not care what occurred prior to the interaction.

Subject Example:

    
import { Subject } from 'rxjs';

// Create a Subject
const subject = new Subject();

// Subscribe to the Subject
subject.subscribe((value) => {
  console.log('New value:', value);
});

// Emit values to the Subject
subject.next('Value 1');
subject.next('Value 2');

// Subscribe to the Subject again
subject.subscribe((value) => {
  console.log('New subscriber:', value);
});

// Emit another value
subject.next('Value 3'); 

//OUPUT
New value: Value 1
New value: Value 2
New value: Value 3
New subscriber: Value 3

We incorporate the Subject from the rxjs library.We instantiate a Subject using the new Subject() constructor.We subscribe to the Subject with the subscribe method, passing in a callback function that we wish to execute whenever the Subject emits a new value.We emit 2 values to the Subject by calling the next for each value.We subscribe to the Subject again.Finally, we emit the value 3 to the Subject.

Here, we can see, the first subscriber receives the emitted values Value 1 and Value 2, whereas the newly subscribed second subscriber only receives the emitted Value 3, therefore affirming that the Subject does not store values, and when new subscribers subscribe, they can only receive emitted values after the subscription.

you may also interested:

Conclusion

When working with RxJS, understanding the differences between BehaviorSubject, Subject, and ReplaySubject will guide you in deciding on which you will use for your use case. Each of these subjects has advantages and disadvantages to bear in mind.

  • BehaviorSubject is very useful when you want to provide initial values to subscribers and let them know what the last value emitted is for when they resubscribe.
  • ReplaySubject is great for preserving a sequence of values for new subscribers and caching purposes.
  • Subject is best for developing your custom observables and/or to signal events.

You will need to consider your need for initial values, if you want to retrieve previous values, and performance when making your decisions. Each subject has its strengths and weaknesses, and by measuring your needs, you should be able to make the best solution for your Angular application.

also view other related posts,