Why we should use RxJs of() function? Why we should use RxJs of() function? angular angular

Why we should use RxJs of() function?


The reason why they're using of() is because it's very easy to use it instead of a real HTTP call.

In a real application you would implement getHeroes() like this for example:

getHeroes(): Observable<Hero[]> {  return this.http.get(`/heroes`);}

But since you just want to use a mocked response without creating any real backend you can use of() to return a fake response:

const HEROES = [{...}, {...}];getHeroes(): Observable<Hero[]> {  return of(HEROES);}

The rest of your application is going to work the same because of() is an Observable and you can later subscribe or chain operators to it just like you were using this.http.get(...).

The only thing that of() does is that it emits its parameters as single emissions immediately on subscription and then sends the complete notification.


Observable.of() is useful for maintaining the Observable data type before implementing an asynchronous interaction (for example, an http request to an API).

As Brandon Miller suggests, Observable.of() returns an Observable which immediately emits whatever values are supplied to of() as parameters, then completes.

This is better than returning static values, as it allows you to write subscribers that can handle the Observable type (which works both synchronously and asynchronously), even before implementing your async process.

//this function works synchronously AND asynchronouslygetHeroes(): Observable<Hero[]> {   return Observable.of(HEROES)  //-OR-  return this.http.get('my.api.com/heroes')  .map(res => res.json());}//it can be subscribed to in both casesgetHeroes().subscribe(heroes => {  console.log(heroes); // '[hero1,hero2,hero3...]'}//DON'T DO THISgetHeroesBad(): Array<Hero> {  return HEROES                             //Works synchronously  //-OR-  return this.http.get('my.api.com/heroes') //TypeError, requires refactor}


In the first example, I assume that the HEROES variable is an array of objects, in which every object corresponds to interface Hero (or is the instance of class Hero). When we call this function somewhere in the code, it will act like this:

heroService.getHeroes()  .subscribe((heroes: Hero[]) => {    console.log(heroes)     // will output array of heroes: [{...}, {...}, ...]  })

It means, that when we use Observable's of creation method with array as argument, on subscription it will emit the whole array, not its' elements one-by-one

In the second example, when we subscribe to Observable, that was returned from getHero() method, it emits only one hero, whose id corresponds to given id.

Basically, when you create Observable with of method and supply arguments to it, on subscription it emits these arguments one-by-one

Here's a good reference