Cold vs Hot Observables In Angular

What is an Observable?

An observer can subscribe to an observable, which is an object that emits items (or subscriber). When an observer subscribes to an Observable, it must also define a reaction to be triggered when the Observable emits a value. This feature allows a system to do several tasks at the same time since it does not need to wait for values to arrive. Observables can be either hot or cold, with the distinction being that they emit items at various times.

What are cold Observables?

A cold Observable does not start emitting until an observer subscribes to it. By default, observables are lazy, which means they only run when an observer subscribes to them. An observer can see the whole series of emitted values because of this characteristic.

import { observable, interval } from 'rxjs';

const observable$ = new Observable((observer) => {
    const interval$ = interval(1000);

    interval$.subscribe (value: number) => {
       observer.next(value); 
    }); 
});
observable$.subscribe((value) => {
    this.logger.log('Subcription #1 - Received:', value);
});
setTimeout() => {
   observable$.subscribe((value) => {
      this.logger.log('Subcription #2 - Received:', value);
   }); 
 }, 2500);

The behavior of a cold Observable is demonstrated in the example above. It’s worth noting that the second subscription’s sequence of values is completely distinct from the first; this is known as unicasting.

What are hot Observables?

As soon as a hot Observable is established, it begins emitting values, and the values it emits are generated outside of it. Multicasting is when the emitted objects of a hot Observable are shared among its subscribers. As a result of this behavior, an observer may begin watching the sequence in the midst.

import { observable, Subject, interval } from 'rxjs';

const subjects = new Subject();

interval(1800).subscribe((value: number) => {
    subject$.next(value);
});

const observable$ = new Observable((observer => { subject$.subscribe (value: number) => {
      observer.next(value);
  });
});

observable$.subscribe((value) => {
    this.logger.log('Subcription #1 - Received:', value);
});

setTimeout() => { observable$.subscribe((value) => {
   this.logger.log('Subcription #2 - Received:', value);
  }); 
}, 2500);

The behavior of a hot Observable is demonstrated in the example above. The second subscription set of received data begins with the number “2,” indicating that it began observing in the middle of the series.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories