Reputation: 1685
I am trying to find an operator that lets me handle the operations performed by forkJoin
and map
in one step instead of two.
My input is an array of observables with varying lengths and I would like to wait until all of them have completed and then create a computed result from the observable outputs that I can subscribe to.
I haven't come across one that allows for those requirements and takes an array as input.
Below an example of a use case:
const observable1 = Rx.Observable.create(
(observer) => {
observer.onNext([1, 2, 3, 4]);
observer.complete();
}
);
const observable2 = Rx.Observable.create(
(observer) => {
observer.onNext([5, 6, 7, 8]);
observer.complete();
}
);
Rx.Observable.magigOperator([observable1, observable2])
.subscribe(
(result) => console.log
);
Now the result I am trying to get is an output of [1,2,3,4,5,6,7,8]
;
I can achieve it by using forkJoin
and map
and running a flatten function, but I was wondering whether there is a single operator that allows me to do this in one go.
Thanks.
Upvotes: 0
Views: 1788
Reputation: 1041
By the way you can create your observables like this (cold observable are automatically completed when values are emitted):
const observable1 = Rx.Observable.of([1,2,3,4]);
const observable2 = Rx.Observable.of([5,6,7,8]);
Observable.forkJoin(observable1, observable2, (...args)=> [].concat(...args));
Thanks kit for you answer.
Upvotes: 0
Reputation: 1761
You don't have to use map
, you can just pass a result selector function as a last argument of forkJoin
, e.g.:
Rx.Observable.forkJoin([observable1, observable2], _.concat)
Also note that observable1
and observable2
in your example do not complete which prevents forkJoin
from emitting the result.
Upvotes: 2
Reputation: 4920
last argument of forkJoin is a function that can manipulate the results from observables. try something like this:
const observable1 = Rx.Observable.create(
(observer) => {
observer.next([1, 2, 3, 4]);
observer.complete();
}
);
const observable2 = Rx.Observable.create(
(observer) => {
observer.next([5, 6, 7, 8]);
observer.complete();
}
);
Rx.Observable.forkJoin([observable1, observable2], (res1, res2) => [...res1, ...res2]).subscribe((res) => {
console.log(res);
});
notice that observer has next no onNext method. Also if you want to you forkJoin the observer has to complete.
Upvotes: 0