Reputation: 115
I have a problem with conditional calls in RxJS.
The scenario is that I have multiple HTTP-Calls inside a forkjoin. But inside the calls there can be dependencies, like I get a boolean back from first call and if that is true the second call should be fired.
This is my code right now:
service.method(parameters).pipe(
tap((data: boolean) => {
foo.bar= data;
}),
concatMap(() =>
service
.method(parameters)
.pipe(
tap((data: KeyValue<number, string>[]) => {
if (true) {
foo.foo = data;
}
})
)
)
)
The problem that I have is that the method now always gets called. My goal is that the method only gets called when the parameter is true, to reduce the amount of calls. I hope somebody can help me.
Upvotes: 0
Views: 415
Reputation: 17762
You can try something like this
service.method(parameters).pipe(
tap((data: boolean) => {
foo.bar= data;
}),
concatMap((data) => data ? // you pass data as parameter and check if true
service // if data is true you return the Observable returned by the service method
.method(parameters)
.pipe(
tap((data: KeyValue<number, string>[]) => {
if (true) {
foo.foo = data;
}
})
) :
of(false) // if data is false you return an Observable containing what you decide it to contain, in this case 'false' but it could be everything
)
)
The idea is that you call the first time the service.method
, pass the result of this call to concatMap
and in there you decide, based on the parameter passed to concatMap
whether to call again service.method
and return the Observable it returns or return an Observable that you create within concatMap
wrapping whatever value you want.
Upvotes: 1