Reputation: 5190
This gives me a headache... following code does work as expected:
const s$ = new Subject<any>();
s$.pipe(
switchMap(
x => {
debugger;
return myService.getSth();
}
)
).subscribe(x => {
debugger;
});
s$.next();
Both debugger
in the switchMap
and subscribe
part are hit.
But if I split it up (I would like to move the whole piping stuff into separate libraries), the debugger in the switchMap
is not hit anymore, meaning the service in this particular example is not called:
const s$ = new Subject<any>();
s$.pipe(
switchMap(
x => {
debugger;
return myService.getSth();
}
)
);
// ...
s$.subscribe(x => {
debugger;
});
s$.next();
What do I miss here?
Upvotes: 5
Views: 11346
Reputation: 84982
Calling .pipe
on an observable (including a subject) doesn't modify what that observable does, but instead it produces a new observable. In your first example, you call subscribe on that new observable. In your second example, you do nothing with the new observable, and then you subscribe to the original non-mapped subject. With nothing referencing the new observable, it is lost.
Save the result of the .pipe
to a variable, and then subscribe to that:
const mapped$ = s$.pipe(
switchMap(
x => {
debugger;
return myService.getSth();
}
)
);
mapped$.subscribe(x => {
debugger;
});
s$.next();
Upvotes: 9