Reputation: 2266
I've been wondering if it's safe to assume that after the using the tap operator, the side effect inside it has completed.
My use case is with ngrx.
...
tap(() => {
this.store.dispatch(new SetValue("Hello World"));
}
}),
switchMap(() => this.store),
select(state => state.value),
tap(state => {
if (state === undefined) {
throw new Error("Couldn't find value");
}
})
SetValue is an class that implements ngrx
export class SetValue implements Action {
readonly type = SET_VALUE;
constructor(public payload: string) {}
}
What I'm trying to implement is to set a value on the store and then check if it's effectively been set.
Can I assume the dispatch has completed after tap operator?
Answer
I used this on Angular Router guards to set initial state by the parameters on the url, so I ended up filtering to only continue when the store has new value
...
tap(() => this.store.dispatch(new SetValue("Hello World"))),
switchMap(() => this.store),
select(state => state.value),
filter(value => value === "Hello World"),
take(1)
Upvotes: 2
Views: 1886
Reputation: 49361
tap
operator takes 3 arguments.
1- if the source observable emits a value, the first argument of the tap
operator is a function that receives that emitted value as an argument.
2- if the source observable goes into an error state, the second argument of the tap
operator is a function that receives that error as an argument. So inside here you can dispatch the error.
3- The third argument is a function that will be invoked any time the observable is marked as complete.
tap(observer, error, complete):Observable
Upvotes: 0
Reputation: 96909
Most operations in RxJS are synchronous so if this.store.dispatch(new SetValue("Hello World"))
won't do any async task it probably will work as expected (it's still just a Subject under the hood).
However, you shouldn't rely on this behavior. NgRx might change it's internals and in general it's better not to rely on synchronicity/asynchronicity of RxJS operators (this has already happened in the past in eg. from()
from RxJS 4 to RxJS 5).
If you want to make sure something has been set then change your new SetValue("Hello World")
effect to emit another action after it's done doing what it needs to do.
Upvotes: 3