RXJS zip of zip (arrays) observable is not firing
Asked Answered
D

2

8

I am trying to get result from a zipped array of observables themselves zips of array of simple observables. As follows:

a(x) {
    const observables = [of(x), of(x+1)];
    return zip(observables);
}

b() {
    const observables = [a(1), a(2)];
    return zip(observables);
}

The rest of the code is asserted to work fine. Actually, when the inner a() function returns a single observable (of array of objects of course, to reflect the zip of observables) the outer zip works fine. Yet when an inner zip is used, the code inside the inner zip is never called.

What am I doing wrong here?

Deci answered 3/11, 2018 at 21:24 Comment(1)
The problem is zip(array) is not the same as zip(arg1, arg2,...).Independent
B
11

How many hours have I spent with this issue..

Try:

zip(...observables);

The parameter has to be spreaded, otherwise your array will be treated as ObservableInput, which is probably not the desired behaviour.

You can include this function as a safe fallback for your use-case:

export function zipArray<T>(array: ObservableInput<T>[]): Observable<T[]> {
    return array.length ? zip(...array) : of([]);
}

And call it like this:

zipArray(observables)
Bother answered 3/11, 2018 at 21:39 Comment(0)
I
1

What is wrong : zip([Obs1, Obs2]) is not the same as zip(Obs1, Obs2).

But there is a trick to make the transition : ...argsArray[] makes an array act as if it was a bunch of arguments (equivalent to *args in python for example).

Also, if you find yourself repeating of operator inside an iterable, then maybe you should consider using from operator.

function a(x) {
    const observables = from([x, x+1]);
    return zip(observables);
}

function b() {
    const observables = [a(1), a(2)];
    return zip(...observables);
}

Test :

b().subscribe(val =>console.log(val))

[[1], [2]]

[[2], [3]]

It is normal that you have [1] instead of 1, because the output of zip returns an array containing the values.

Independent answered 3/11, 2018 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.