Maxouhell Maxouhell - 28 days ago 7
TypeScript Question

Useless server call while combine filter with withLatestFrom

I have this observable :

const myObservable = Observable.combineLatest(v1, v2)
.filter(([v1, v2]: [boolean, boolean]) => v1 && v2)
.withLatestFrom(myServerCall)
.subscribe((data) => {
console.log(data);
});


Where myServercall is an http request.

I don't want to make an http call when my filters are not ok. But it always call my server even if it never come inside my subscribe function.

What can I do to avoid useless server call ?

Answer Source

The withLatestFrom isn't a good choice because it subscribes to all source Observables (this means myServerCall as well) and that's where it makes the remote call you don't want.

I think switchMap makes more sense here.

const myObservable = Observable.combineLatest(v1, v2)
    .filter(([v1, v2]: [boolean, boolean]) => v1 && v2)
    .switchMap(() => myServerCall())
    .subscribe((data) => { 
        console.log(data);
    });