Observable in RxJs (Hot & Cold)

Observable in RxJs (Hot & Cold)

Observables are the newest thing in town and being a frontend dev. They will never leave alone.

What are Observables?

Let's start with a simple example of a Candy Shop. If you like Cadbury Dairy Milk you go to the shop and try to buy the same but it's not available. So you either wait there or give your number to the candy shop owner to call you when it arrives. So with this example we get to eat dairy milk, learn Consumer Problem, Push Model and Basics of Observable.

import { Observable } from 'rxjs';
// Synchronus way
let observable = Observable.create((subscriber: any) =>{
    subscriber.next(‘Candy Arrived’);
    subscriber.next( ‘Lets Run to the shop’ );
})

observable.subscribe((data)=>{
   console.log(data);    
})

Output :
Candy Arrived
Lets Run to the shop

Observable are a progressive way of handling events within a stream asynchronusly. These observables emit values that define the callback functions such as error(), next() and complete().

Phases of Observable

  1. Creation
  2. Subscription
  3. Execution
  4. Unsubscribe

Creation of Oervable

// Creation Using http method
public getTitle(url):Observable<String[]> {
  return http.get(url);
}

// Observable.create
let observable = Observable.create((subscriber: any) =>{
    subscriber.next(‘Candy Arrived’);
    subscriber.next( ‘Lets Run to the shop’ );
})

You can also Read Power of Generators in Javascript

Subscription of Observable

this.postService.getTitle(url).subscribe({
next:()=> {},
error: ()=> {},
complete: ()=> {}
});

Execution of Observable

The statements inside the create block is called execution. You can perform any task inside it and return value using next(), error(), complete().

    subscriber.next(‘Candy Arrived’);
    subscriber.next( ‘Lets Run to the shop’ );

UnSubscribe of Observables

import { Subscription } from "rxjs";

export class SubscriptionDemo implements OnInit,OnDestroy  {
      private subscriptions: Subscription[] = [];
      ngOnInit(): void {
        this.subscriptions.push(this.postService.getTitle(url).subscribe({
          next:()=> {},
          error: ()=> {},
          complete: ()=> {}
          }));
      }

      ngOnDestroy (): void {
          this.subscriptions.forEach((subscription: Subscription): void => {
            subscription.unsubscribe();
        });
      }
}

You can also Read Recursion Day 1

Important Points about Observables

Observables are lazy whereas promises are not Observables handle multiple values unlike promises and its a stream Observables are cancelable using unsubscribe Observables provide many operators such as pipe,map,take,filter and many more

Lets Move On then

Hot and Cold Obserables

Hot Observables

  • Hot Observables emit the same data to all subscribers as the data is produced outside the Observable.

  • Hot observables are multicast (Share value between multiple subscribers).

Cold Observables

  • Cold Observables start to emit only when we subscribe.

  • Cold Observables are unicast.

  • Cold Observables create data source inside observable.

//Cold Observable the value generated is inside the obervable so every subscription new value
const ColdGenerator = ()=> {
  return new Observable((subscriber)=> {
      const value = Date.now();
      subscriber.next(value);
    });
}

//Hot Observable the value generated is Outside the obervable so every subscription same value
const HotGenerator = ()=> {
  const value = Date.now();
  return new Observable((subscriber)=> {
      subscriber.next(value);
    });
}

You can always see the example here on Stackblitz

Did you find this article valuable?

Support ANURAG SARAN by becoming a sponsor. Any amount is appreciated!