Skip to main content

Observable, Subject , Behavior Subject using RxJS:

 




Create an Observable using RxJS: 

Import the Observable            

        
        import { Observable } from 'rxjs';

The Observable execution deliver three types of values:

  • "Next" - sends a value such as a Number, a String, an Object, etc.
  • "Error - sends the Error or exception.
  • "Complete" - does not send a value after the Complete
                 
                 ngOnInit(): void {
                  this.observable$ = new Observable(subscriber => {
                    subscriber.next(1);
                    subscriber.next(2);
                    subscriber.next(3);
                    subscriber.complete(); //Complete the subscribing here
                    subscriber.next(4);  // Value not send after complete
                  });
                  this.observable$.subscribe(value => {
                    console.log(value);
                  }, err => {
                    console.log('err'err);
                  });
                }


                ngOnDestroy() {
                  this.observable$.unsubscribe();
                } 


Suppose when we navigate to a different page that we don’t want to leave the subscription remains open. So In ngOnDetsroy()  life cycle hook  unsubscribe the observable.With this.observable$.unsubscribe(); you can cancel the ongoing execution:

 

Output:



Subject:

Subject is also observable, it allows value to be multicasted to many observers. Observables are unicast and Subjects are multicast.

When we create an observable each time, it will create a single instance It means we cannot reuse or share the observers.

Each observable has its own observer and it cannot interact with each other because it is wrapped. We can subscribe to the observable more than once but the observers in it don’t know about each other.

just look at the example below.

 


   ngOnInit() {
    this.mySubject$ = new Subject();
    this.mySubject$
        .subscribex => 
            
                console.log('Initial subscription'x);
            });
    this.mySubject$.next(1);
    this.mySubject$.next(2);
    this.mySubject$
        .subscribex => 
            
                console.log('Final subscription'x);
            });
    this.mySubject$.next(3);
    this.mySubject$.next(4);
}

 

Output:

In the example above, the initial subscription gets all the four values but the final subscription gets only the last two values. Because we are subscribing only after the first two get subscribed by the initial one.
To get the value, even if it is passed before we can use Behavior Subject.

Subject are shareable but not reusable. Once we call error or complete on Subject we can't reuse it.again.please refer the below code for it.

ngOnInit() {
    this.mySubject$ = new Subject();
    this.mySubject$    
        .subscribex => 
            { 
                console.log('Initial subscription'x);
            });
    this.mySubject$.next(1);
    this.mySubject$.next(2);
    this.mySubject$.complete(); // Complete
    this.mySubject$
       .subscribex => 
            { 
                console.log('Final subscription'x);
            });
    this.mySubject$.next(3);
    this.mySubject$.next(4);
}


Output:


Behavior Subject:

Behavior subject stores the latest value. It holds the latest value emitted to consumers. Behavior subject should be initialized.It always requires a starting value.

  ngOnInit() {
    this.behaviorSubject$ = new BehaviorSubject(1); //Initial value mentioned
    this.behaviorSubject$
        .subscribex => 
            { 
                console.log('Initial subscription'x);
            });
    this.behaviorSubject$.next(2);
    this.behaviorSubject$.next(3);
    this.behaviorSubject$
        .subscribex => 
            { 
                console.log('Final subscription'x);
            });
    this.behaviorSubject$.next(4);
    this.behaviorSubject$.next(5);
   }



Output:


In the above example, For the initial subscription, it holds the current value which is 1, then it prints the remaining value for the initial subscription. For the final subscription, it prints the current value 3 which is from the initial subscription then it prints the remaining values.

ReplaySubject:

To get all the values that passed through the subject since from the beginning we can use ReplaceSubject. The ReplaceSubject will save all the values and give them to each subscriber event after it gets completed.

ReplaceSubject doesn't require an initial value.

 ngOnInit() {
    this.behaviorSubject$ = new ReplaySubject();
    this.behaviorSubject$
        .subscribex => 
            { 
                console.log('Initial subscription'x);
            });
    this.behaviorSubject$.next(2);
    this.behaviorSubject$.next(3);
    this.behaviorSubject$
        .subscribex => 
            { 
                console.log('Final subscription'x);
            });
    this.behaviorSubject$.next(4);
    this.behaviorSubject$.next(5);
  }

Output:
 

In the above example, both subscriptions got all the values.

Comments

Popular posts from this blog

React JS - Beginners

  React JS React is an open-source JavaScript library for building user interfaces or UI components. It was created at Facebook and open-sourced in March of 2013. It is used on social platforms like Instagram, Facebook, Twitter. And It is used on content delivery platforms like NetFlix, Spotify. Beyond Web applications, you can create native mobile applications using React Native. Check your system node and npm version. Node version should be greater than 8.10 and for npm, we need version 5.6.   Create a new React-app: Command to create a new react app: npx create-react-app new-app   To start the react app: npm start   Folder Structure: package.json – It contains all the project dependencies. src folder – It contains the files required to build the application public folder – when we ready to build the app for production all the built files will be placed in the public folder.   Create a React element: Elements are the building blocks of React apps

Convert Base64 code to PDF file in Angular

Component.ts: import { DomSanitizer } from '@angular/platform-browser' ; base64Code = 'your base64 code ' ; byteCharacters : any ; pdfUrl : any ; constructor ( public sanitizer : DomSanitizer ) { } convertToPdf () { // tslint:disable-next-line:max-line-length this . byteCharacters = this . base64Code ; // atob() function decodes a string of data which has been encoded using base-64 encoding const byteCharacters = atob ( this . base64Code ); const byteNumbers = new Array ( byteCharacters . length ); for ( let i = 0 ; i < byteCharacters . length ; i ++) { byteNumbers [ i ] = byteCharacters . charCodeAt ( i ); } const byteArray = new Uint8Array ( byteNumbers ); const blob = new Blob ([ byteArray ], { 'type' : 'application/pdf' }); this . pdfUrl = URL . createObjectURL ( blob ); } Component.html: < embed [src] = "sanitizer.bypassSecurityTr

Angular Architecture

  Angular Architecture: Angular is a platform and framework to build single-page client applications using HTML and TypeScript. It is written in Typescript.    The basic building blocks are NgModules. It provides compilation context to components. An angular app has always a root module to enable bootstrapping.                                                               Architectural diagram src: Angular.io   The main building blocks of Angular applications:              Modules              Component             Metadata              Templates              Directives                Data binding              Services              Dependency injection Modules : Angular applications are modular and every Angular app has a root module, which provides the bootstrap mechanism.  An angular module is a class with an @NgModule decorator. NgModules import the functionalities form other NgModules just like other JavaScript modules. We can divide