Working with Observable in angular | Akashminds


Working with Observable in angular

Observable has now become most important part of Rxjs. It provides data sharing in asynchronous programming. here are many reasons we prefer using observable instead of promise. Observable can be accessed anywhere in the application, the only way to access it by subscribing it.

An Observable is like a stream and it allows us to send one or more events at a time. it is up to your requirement if you want to handle 0, 1 or a number of events, same API can be utilized for each event.

Observable has more advantages over promise. it can only be accessed or handled if you subscribe to it and that why Observables are called lazy. but if we talk about promise , it starts immediately and that can be caused as memory leakage. Observable has a powerful feature over promise to be cancellable, If there is no further need of the async operation then subscription of the observable allows us to cancel or complete the process in Angular

We can use various Rxjs operators like map, pipe, reduce and more where every individual stream can be mapped or modified to get the desired data.

There are around 110 operators in Rxjs

Lets go more deep into Observable behavior, For that we need to understand Observers.

Observers are special types of function that we pass into subscribe to get expected outputs from Observable and this is quite simple we have three Observers next(), error() and complete() in an observables. when an Observable produces value it informs Observer next(), when an error occurs then error() get called and when there is no more value to be sent from Observable then it calls complete().


// Create simple observable that emits three values
const myObservable = of(1, 2, 3);

// Create observer object
const myObserver = {
  next: x => console.log('Observer got a next value: ' + x),
  error: err => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};

// Execute with the observer object
myObservable.subscribe(myObserver);

// Logs:
// Observer got a next value: 1
// Observer got a next value: 2
// Observer got a next value: 3
// Observer got a complete notification

Creating Rxjs observable

Observable is a core concept of Rxjs nowadays. It is used in asynchronous programming to share data over applications. There are so many ways to store data into the application using variables, browser storages etc.
 Ever wondered why we use observables so much? Because it just not provide asynchronous programming but save our application from many problems like redundancy,  memory leakage etc.

If you haven't gone through my last article about Observable, have a look on here.

So , let start creating an observable.

Convert String to Observable

we are going to create observables from string , numbers , array and objects. We can use Observable constructor to create an Observable and return.
In the first example we are going to create Observable that emit multiple string value.
 var obs = Observable.of('one', 'two', 'three');
    obs.subscribe(
      res => console.log(res),
      err => console.log(err),
      () => console.log('Completed!')
    );
   output:
   one
   two
   three

Convert integer to Observable

We can use Of Operator to pass integer, array of integers to Observable 
We can directly import Of operator from rxjs class.it can emit multiple value one after the other and at the end it sends complete into Observer Object that the operation is now finished.
Here we are passing a number.

Convert an Array to Observable

If you want to convert an array into observable then Of Operator can also be used to return an observable and you can use that observable to your desire place by subscribing it here is an example.
Also 
we can use from operator from rxjs that is used to convert an array into observable, with the help of from operator we can easily convert an array, object to observable.

  const array3 = [1, 2, 3, 4, 5, 6, 7]
    const obsfrom1 = from(array3);
    obsfrom1.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))

Summary

In this section , we focused on Observable and take advantage of them while development , the main part of observable is that they are asynchronous in behavior and can work with multiple stream at a time. I hope you liked the article ,consider sharing and subscribing.

Post a Comment

1 Comments