Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS zip of zip (arrays) observable is not firing

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?

like image 465
Tomer Raziel Borenstein Avatar asked Nov 03 '18 21:11

Tomer Raziel Borenstein


Video Answer


2 Answers

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)
like image 189
ggradnig Avatar answered Nov 02 '22 22:11

ggradnig


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.

like image 20
madjaoue Avatar answered Nov 02 '22 23:11

madjaoue