Search code examples
arraysmergerxjscombinelatest

What's the elegant way of writing CombineLatest with conditional arguments?


In a non-async code, I do the following:

    const x = [
        ...(isY ? [Y]: []),
        ...(isZ ? [Z] : [])
    ];

How would you elegantly write this structure when isY and isZ are Observables<boolean>, and x to be an Observable<Object[]>.

I can do this with al kinds of mappings, but nothing looks clean or elegant.


Solution

  • combineLatest operator is best used when you have multiple, long-lived observables that rely on each other for some calculation or determination. Be aware that combineLatest will not emit an initial value until each observable emits at least one value.

    You can have a look at the explanation for combineLatest.

    const x: Observable<any[]> = combineLatest(isY$, isZ$).pipe(
        map([isY, isZ] => {
            return [
                ...(isY ? [Y]: []),
                ...(isZ ? [Z]: [])
            ]
        })
    )
    

    EDIT: You can also use the combineLatest project-function, so it can even be terser by doing

    const x: Observable<any[]> = combineLatest(isY$, isZ$, (isY, isZ) => [ 
       ...(isY ? [Y]: []), 
       ...(isZ ? [Z]: []) 
    ])