DEV Community

Deepa Chaurasia
Deepa Chaurasia

Posted on

How to make Custom Observable, methods to use and operators in rxjs?

To make custom observable ,you have to follow these steps:

Import observable from rxjs
Image description

_
In your ts file declare const customObservable("you can use any other name")_

Image description

You assign Observable.create in your variable, and as the name suggests it will create the observable.

Observable.create method have observer as argument by default ,provided by angular.And we use this observer to further call methods like next,error or complete.

You must we wondering what does these methods do?

Well there are three methods and these are their operation

  • next() - This method is used to emit new value.
  • error() - This method handles your error notification,if it's http request you get this automatically .
  • complete()-Your this method will run when your observable will complete.

You can write any logic inside 'Observable.create' according to your requirement.

In the above, basically we have made a custom observable which have setInterval method ,It is doing nothing much but printing your values after incrementing it.

Remember after making Observable you definitely will subscribe it that's how it works.

Image description

This is how i have subscribed my customObservable,you may notice I have used pipe and map why????

So suppose you have a requirement where you have to transform your data before subscribing it how will you do that?

That pipe right there is the method we use for doing these operations and the map out there itself is a operator.

What is Operator??

Operator are the constructs , which is used for transforming data of observables.

Operators we are using here belongs to 'rxjs',You might want to search Rxjs Operators for complete understanding .

Every observable has pipe method ,with the help of which we perform operations as i mentioned earlier.

Now as you can see:

Image description

Here it will first map every data and transform it to 'Round' :data instead of just data.

Simply that's how it works.

*Thankyou for reading ,Please like share *

Top comments (0)