Reputation: 14917
I'm not sure why subscribe
works with BehaviourSubject
but not pipe
.
For example, the code below prints out?
subscribe: 123
subscribe: 456
Why doesn't it also print
pipe: 123
pipe: 456
Code:
import {tap } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';
const subject = new BehaviorSubject(123);
subject.subscribe(p => console.log("subscribe: " + p));
subject.pipe(
tap(p => {console.log("pipe:" + p);})
)
subject.next(456);
Upvotes: 1
Views: 2678
Reputation: 71
subject.pipe(
tap(p => {console.log("pipe:" + p);})
)
You are only tapping into the observable here. You will need to subscribe separately in this subject for the tapping to work. The following code will give you the desired console log:
subject.pipe(
tap(p => {console.log("pipe:" + p);})
).subscribe();
If you must subscribe only once, then you could try the following code:
const abc$ = new BehaviorSubject(123).asObservable().pipe(
tap((val) => console.log('pipe: ', val))
);
abc$.subscribe((val) => console.log('subscribe: ', val));
Upvotes: 2