https://stackoverflow.com/questions/59577497/what-useful-function-does-tap-operator-bring-in-rxjs
By piping Rxjs operators together we start out with one observable, and end with another observable.
const userBooks$ = getUser(emailAddress).pipe(
switchMap(user => getBooksForUser(user.id));
- We start out with a method that returns an
Observable<User>
- We pipe this to
switchMap
and call another method that returns andObservable<Book[]>
This is the functional reactive nature of Rxjs. You pipe together operators to transform streams.
You can think of these as list comprehension methods like map, reduce, filter, merge ... but for asynchronous streams -- not for arrays or lists.
So if all we can do with pipe an Observalbe<T1>
to operators and get Observable<T2>
out -- how do we do other things, like call console.log(..) -- or show an error to the user? Or whatever we need to do that interacts with the world outside the chain of Rxjs operators. Anything that touches state, calls something, outside of the operators is a side effect.
const userBooks$ = getUser(emailAddress).pipe(
tap(user => console.log('user id: ', user.id),
switchMap(user => getBooksForUser(user.id).pipe(
tap(books => console.log('books: ', JSON.stringify(books)));
No comments:
Post a Comment