Observable and Subjects in Angular

In this article, we are going to discuss the basics of observable and subject. Also, the difference between them is explained with the help of practical examples and the different types of subjects.

Agenda

  • What is Angular?
  • Observable in Angular
  • Subject in Angular
  • Difference between Observable and Subject with a Real-Time Use Case
  • Types of Subjects in Angular with Examples

Prerequisites

  • Basic understanding of typescript
  • VS Code
  • Angular CLI
  • NodeJS

What is Angular?

Angular is a popular open-source JavaScript framework for building web applications. It was developed by Google and is currently maintained by the Angular Team at Google. Angular allows developers to create dynamic, single-page applications (SPAs) and provides a structured approach to building complex web applications.

Observable in Angular

  • In Angular, Observables are part of the Reactive Extensions for JavaScript (RxJS) library.
  • Observables provide support for passing messages between parts of your application.
  • Observables are a powerful feature used extensively in reactive programming to handle asynchronous operations and data streams.
  • Observables provide a way to subscribe to and receive notifications when new data or events are emitted, enabling you to react to changes in real-time.

Subject in Angular

  • An RxJS Subject is a special type of Observable that allows values to be multicast to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.
  • A Subject is like an observable but can be multicast to many Observers. Subjects are like Event Emitters: they maintain a registry of many listeners.
  • It is a part of the Reactive Extensions for JavaScript (RxJS) library, which is included by default in Angular projects.

Difference between Observable and Subject with Real-Time Use Case

Observable and Subject are both part of the Reactive Extensions for JavaScript (RxJS) library and are used for managing asynchronous data streams and event handling in Angular. However, they have some key differences

Difference between Observable and Subject

Types of Subjects in Angular with Examples

Following are the types of Subjects available in the RxJS library, which you can use for different scenarios:

1. Subject

  • The Subject is a basic implementation of a subject in RxJS.
  • It is a multicast observable that maintains a list of observers and notifies all of them when a new value is emitted using the next() method.
  • It does not have an initial value, so subscribers only receive values emitted after they subscribe.
  • This is a good option when you need a simple multicast subject without any additional features.
//------------------Observables are unicast-----------------
//observable
let observable = new Observable<number>(ele =>
  ele.next(Math.random()))

//first subscriber
observable.subscribe(result => {
  this.first_subscriber_observable = result;
  console.log(result)
})

//second subscriber
observable.subscribe(result => {
  this.second_subscriber_observable = result;
  console.log(result)
})

//third subscriber
observable.subscribe(result => {
  this.thrid_subscriber_observable = result;
  console.log(result)
})
//--------------------------------------------------------

//------------------Subjects are multicast-----------------
//subject
let subject = new Subject<number>()

//first subscriber
subject.subscribe(result => {
  this.first_subscriber_subject = result;
  console.log(result)
})

//second subscriber
subject.subscribe(result => {
  this.second_subscriber_subject = result;
  console.log(result)
})

//third subscriber
subject.subscribe(result => {
  this.third_subscriber_subject = result;
  console.log(result)
})

subject.next(Math.random())
//--------------------------------------------------------

Subjects in Angular

2. BehaviorSubject

  • The behavior subject is another type of subject in RxJS.
  • It has an initial value and will immediately emit the initial value to any subscriber as soon as they subscribe, even if no values have been emitted yet using the next() method.
  • After the initial value is emitted, it behaves like a regular Subject and notifies subscribers about new values emitted using next().
  • This is useful when you want to provide the last known value to new subscribers, such as the current state of an application or the latest data fetched from an API.
//----------Behavior Subject has default or last emitted value---------------
var behaviorSubject = new BehaviorSubject<number>(123)

behaviorSubject.subscribe(ele => {
  this.first_subscriber_behaviorSubject = ele
  console.log(`first subscriber ${ele}`)
})

behaviorSubject.next(456)

behaviorSubject.subscribe(ele => {
  this.second_subscriber_behaviorSubject = ele
  console.log(`second subscriber ${ele}`)
})

//--------------------------------------------------------------------------

BehaviorSubject

3. ReplaySubject

  • The ReplaySubject is a subject that can buffer and replay a specific number of values to new subscribers.
  • When you create a ReplaySubject, you can specify the buffer size, which determines how many previous values should be replayed to new subscribers.
  • This is useful when you want to provide a history of values to new subscribers or when you need to cache values for later use.
 //---------------Replay subject buffers old values not default one-----------

const replaySuject = new ReplaySubject(2) //If we we want to show only last 2 buffered value otherwise it will show all

replaySuject.next(111)
replaySuject.next(222)
replaySuject.next(333)

replaySuject.subscribe(e => {
  console.log(`First Subscriber ${e}`)
  this.first_subscriber_replaySubject.push(e);
})

//new values show to existing subsriber
replaySuject.next(444)

replaySuject.subscribe(e => {
  console.log(`Second Subscriber ${e}`)
  this.second_subscriber_replaySubject.push(e);
})

replaySuject.next(555)
//--------------------------------------------------------------------------

ReplaySubject

4. AsyncSubject

  • The AsyncSubject is a subject that only emits the last value when it completes.
  • It will not emit any values until the subject’s complete() method is called. When completed, it will emit the last value (if any) to subscribers.
  • This is useful when you need to wait for an operation to complete before emitting a final value, such as waiting for an HTTP request to finish and emitting the response as a single value.
//---------------Async subject sends the latest value to subscribers when it's completed-----------
const asyncSubject = new AsyncSubject<number>();

asyncSubject.subscribe(e => 
  {
    console.log(`First Subscriber: ${e}`)
    this.first_subscriber_asyncSubject=e;
});

asyncSubject.next(111);
asyncSubject.next(222);
asyncSubject.next(333);
asyncSubject.next(444);

asyncSubject.subscribe(e => {
  console.log(`Second Subscriber: ${e}`)
  this.second_subscriber_asyncSubject=e;
});

asyncSubject.next(555);
asyncSubject.complete();

//--------------------------------------------------------------------------

AsyncSubject

GitHub URL

https://github.com/Jaydeep-007/angular-subject-and-observable

Conclusion

In this article, we discussed the basics of subjects and the difference between observable and subject with different types and examples.

Happy Coding!