Why we should use RxJs of() function?

31,840

Solution 1

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.

Solution 2

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 asynchronously
getHeroes(): 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 cases
getHeroes().subscribe(heroes => {
  console.log(heroes); // '[hero1,hero2,hero3...]'
}

//DON'T DO THIS
getHeroesBad(): Array<Hero> {
  return HEROES                             //Works synchronously
  //-OR-
  return this.http.get('my.api.com/heroes') //TypeError, requires refactor
}
Share:
31,840
Aref Zamani
Author by

Aref Zamani

Updated on July 09, 2022

Comments

  • Aref Zamani
    Aref Zamani almost 2 years

    in service section of angular.io tutorial for angular2 I hit a method named of.for example :

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

    or in below sample:

    getHero(id: number): Observable<Hero> {
      // Todo: send the message _after_ fetching the hero
      this.messageService.add(`HeroService: fetched hero id=${id}`);
      return of(HEROES.find(hero => hero.id === id));
    }
    

    in angular.io Just explained

    used RxJS of() to return an Observable of mock heroes (Observable<Hero[]>).

    and It was not explained why we should use of operator and exactly what does it do and what are its benefits?

  • Brandon Miller
    Brandon Miller over 6 years
    I think he's asking why use Of() in the first place if only one object is being returned in both examples.
  • Renaud
    Renaud over 4 years
    of also works synchronously unless you specify you different Scheduler
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 4 years
    if you want to simulate request you can add some delay as follows of(HEROES).pipe(delay(5000)); - the result will be emitted 5s after subscription. This pipe-delay is also handy if you want to simulate some delay for real this.http... request - which is useful sometimes for some debugging scenarios