tap() isn't triggered in RXJS Pipe
Asked Answered
T

2

23

I have to ways of doing the same thing, although I prefer the first one. But the first approach doesn't seem to work. (the tap() is not triggered)

// does not work
this.actions$.pipe(
    ofType(LayoutActions.Types.CHANGE_THEME),
    takeUntil(this.destroyed$),
    tap(() => {
        console.log('test')
    }),
);
// works
this.actions$.ofType(LayoutActions.Types.CHANGE_THEME).subscribe(() => {
    console.log('test')
});
Tergal answered 5/9, 2018 at 15:29 Comment(0)
E
59

Imagine RxJS pipes like actual, physical pipes with a valve at the end. Each pipe will "modify" the liquid that is flowing through it, but as long as the valve at the end is closed, nothing will ever flow.

So, what you need, is to open the valve at the end. This is done by subscribing to the observable pipe. The easiest solution is:

this.actions$.pipe(
    ofType(LayoutActions.Types.CHANGE_THEME),
    takeUntil(this.destroyed$),
    tap(() => {
        console.log('test')
    }),
).subscribe(_ => console.log("water is flowing!"));
Educator answered 5/9, 2018 at 15:39 Comment(3)
Never used pipe before and had the same problem as OP. Thank you so much, now the water flows!!! hahaValvulitis
Excellent! Thank youPennipennie
awsome answer. hell yeah.Boggle
E
8

pipe creates new Observable thus you must asssign it and then subscribe to that isntance. In your case you are ommiting pipe return thus you end up with plain, unmodified Observable without any extra pipe actions.

Also remember that most likely you will have to subscripbe in order to pipe (and tap) to work.

try

this.actions$=this.actions$.pipe(
    tap(()=>console.log("First tap")),
    ofType(LayoutActions.Types.CHANGE_THEME),
    takeUntil(this.destroyed$),
    tap(() => {
        console.log('Last tap')
    }),
);

this.actions$.subscribe(() => {
    console.log('subscribtion')
});
Ette answered 5/9, 2018 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.