I am trying to execute a method 1000
milliseconds after all items in pipe finish, and I don’t want the result, nor do I want it to change the current value of the pipe. What I have here is what I am doing which works, but it isn’t using rxjs completely with the setTimeout
.
selectionChanged$ = this.selectionChanged.pipe(
map(() => this.someValue),
tap(() => /* do stuff */),
tap(() => setTimeout(() => this.doSomething(), 1000))
);
I then tried this, but it does two things that I don’t want:
- It waits for the timer to complete
- It changes the final result to a
number
doSomething$ = timer(1000).pipe(
tap(() => this.doSomething()),
);
selectionChanged$ = this.selectionChanged.pipe(
map(() => this.someValue),
tap(() => /* do stuff */),
switchMap(() => this.doSomething$)
);
Is there a way to get the desired result without (aka "Set it and forget it"):
- Using
subscribe()
- Waiting for the timer to complete
- Modifying the final result
2
Answers
Do you mean like this? I use
delay
of1000s
and then finally using map, set the last emit value to zero.Stackblitz Demo
You could do something like this:
The idea here is to create an observable that immediately emits the value (
startWith
), then after the duration (timer
) executes the side effect function. We useignoreElements
to block emission from the timer.The benefit here over using
setTimeout
is that if the consumer unsubscribes, the side effect logic will not be executed.You could even roll it into a custom operator:
Here’s a StackBlitz.