Friday, 25 June 2021

How to create a function which return observable | Create our own observable


There are multiple inbuild methods provided by 'rxjs' which return observable (like Interval) but if we want to create our own function which return Observable then we can use Create method of observable.

Observable in rxjs is implementation of Observer design pattern, There are two main parts of this pattern

1.Observable 
2.Observer.

We can subscribe/unsubscribe to observable, Observer exposes 3 methods next, error and complete.
we will try to understand all this things by an example. as mentioned in title, we want to create our own observable i.e. we have a funciton/method which will return observable<T>.

suppose I have a function will return a string , but instead of string you want to return Observable<string> from this method/function.

GetObseravleByCreate_simple(): Observable<string>
    {       
        let obs=new Observable<string>(subscriber=>{
            
                subscriber.next("Hello");
                subscriber.error();
                subscriber.complete();           
           
        })
        return obs;

    }

Above operation is very simple when you subscribe this method you will get simple string.
below example simulates a long running operation with the help of setTimeOut function of JS.

 GetObseravleByCreate(): Observable<string>
    {
        let obs=new Observable<string>(subscriber=>{
           
            setTimeout(function() {
                subscriber.next("Hello after 1 second");
                console.log("Observable:create");
                subscriber.complete();

              }, 1000);
            
           // subscriber.error();
        })
        return obs;

    }

Summary : we need to create a instance of Observable<T> ,in constructor we will pass a callback which gives us subscriber instance, on this instance we can call next() method, in other word when we are done with our operation we need to call next() by passing result into it. similarly we can call error() or complete to notify subscriber about error in operation or completion of operation respectively.

At client end: 

           this.service.GetObseravleByCreate_simple().subscribe(x=>{this.obsStr=x;},err=>{});
      //or 
    this.service.GetObseravleByCreate_simple().subscribe(x=>{this.obsStr=x;});

No comments:

Post a Comment

Parent child component communication in Angular. (Approach-1)

  If we will make a property in Child component and somehow if it's a two-way bindable property, then Child would be able to set its val...