I recently notice that I can return a value inside .pipe()
but not inside .subscribe()
.
What is the difference between these two methods?
For example if I have this function, let's call it 'deposit', which is supposed to return the account balance, if I do this:
deposit(account, amount){
return this.http.get('url')
.subscribe(res => {
return res;
}
}
It returns an observable and if I do this:
deposit(account, amount){
return this.http.get('url')
.pipe(
map(res => {
return res;
});
);
}
It returns the account balance as expected.
So why?
Using pipe to combine operators The pipe method accepts operators such as filter , map , as arguments. Each argument must be separated by a comma. The order of the operators is important because when a user subscribes to an observable, the pipe executes the operators in a sequence in which they are added.
Observables are not executed until a consumer subscribes. The subscribe() executes the defined behavior once, and it can be called again. Each subscription has its own computation. Resubscription causes recomputation of values.
Remember: . pipe() is not . subscribe()! This represents a great opportunity to get in touch with the confusing parts of RxJs which can be easy to forget once one masters the APIs and focuses on the implementation of the features instead.
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.
The pipe
method is for chaining observable operators, and the subscribe
is for activating the observable and listening for emitted values.
The pipe
method was added to allow webpack to drop unused operators from the final JavaScript bundle. It makes it easier to build smaller files.
For example if I have this function, let's call it 'deposit', which supposed to return the account balance, if I do this:
deposit(account, amount){ return this.http.get('url') .subscribe(res => { return res; } }
It returns an observable
That isn't what it returns. It returns the Subscription
object created when you called Subscribe
.
and if I do this:
deposit(account, amount){ return this.http.get('url') .pipe( map(res => { return res; }); ); }
It returns the account balance as expected.
That isn't what it returns. It returns an Observable
which uses a map
operator. The map operator in your example does nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With