Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we should use RxJs of() function?

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?

like image 265
Aref Zamani Avatar asked Dec 19 '17 14:12

Aref Zamani


People also ask

What is of () in RxJS?

RxJS' of() is a creational operator that allows you to create an RxJS Observable from a sequence of values. According to the official docs: of() converts the arguments to an observable sequence. In Angular, you can use the of() operator to implement many use cases.

Why we should use RxJS?

The RxJS library is great for handling async tasks. It has a large collection of operators in filtering, error handling, conditional, creation, multicasting, and more. It is supported by JavaScript and TypeScript, and it works well with Angular.

What does pipe () do RxJS?

RxJS' pipe() is both a standalone function and a method on the Observable interface that can be used to combine multiple RxJS operators to compose asynchronous operations. The pipe() function takes one or more operators and returns an RxJS Observable.

Why should I use observables?

Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.

What is RxJS used for?

These might be used for continous streams, such as events, or pure operations with no arguments such as fetching master data from a server. RxJS provides us with subjects, which are both observables and observers. Additionally to plain subjects, we have some other implementations with added features:

What is a subject in RxJS?

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. and it goes on to give examples but I'm looking for a basic ELI5 explanation.

When to use observables vs RxJS?

A: It is helpful to qualify when to use observables by context. For example, If your action triggering multiple events — use RxJS. If you have a lot of asynchrony and you are trying to compose it together — use RxJS. If you run into situations where you want to update something reactively — use RxJS.

What are streams in RxJS?

Streams are important to understand because they are facilitated by RxJS Observables. An Observable is basically a function that can return a stream of values to an observer over time, this can either be synchronously or asynchronously. The data values returned can go from zero to an infinite range of values. We made a custom demo for . No really.


2 Answers

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.

like image 129
martin Avatar answered Oct 07 '22 17:10

martin


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 } 
like image 39
zhark Avatar answered Oct 07 '22 18:10

zhark