I\'m trying to user forkJoin on two Observables. One of them starts as a stream... If I subscribe to them directly I get a response, forkJoin isn\'
For me the combineLatest operator was the solution!
Observable.forkJoin([
_someService.getUsers(),
_someService.getCustomers(),
])
.subscribe((data: [Array<User>, Array<Customer>]) => {
let users: Array<User> = data[0];
let customer: Array<Customer> = data[1];
}, err => {
});
//someService
getUsers():Observable<User> {
let url = '/users';
return this._http.get(url, headers)
.map(res => res.json());
}
getCustomers():Observable<Customer> {
let url = '/customers';
return this._http.get(url, headers)
.map(res => res.json());
}
A very common problem with forkJoin is that it requires all source Observables to emit at least one item and all of them have to complete.
In other words if this.statuses$ or this.companies$ doesn't emit any item and until they both complete the forkJoin won't emit anything.
this.statuses$.subscribe(
res => console.log(res),
undefined,
() => console.log('completed'),
);
forkJoin emits only when all inner observables have completed.
If you need an equivalent of forkJoin that just listens to a single emission from each source, use combineLatest + take(1)
combineLatest(
this.statuses$,
this.companies$,
)
.pipe(
take(1),
)
.subscribe(([statuses, companies]) => {
console.log('forkjoin');
this._countStatus(statuses, companies);
});
As soon as both sources emit, combineLatest will emit and take(1) will unsubscribe immediately after that.
The forkJoin didn't work so I used the below code to solve my problem. With mergeMap you can map the result of the outer subscription to the inner subscription and subscribe to it as you wish
this.statuses$.pipe(
mergeMap(source => this.companies$.pipe(
map(inner => [source , inner])
)
)
).subscribe(([e , r]) => {
console.log(e , r);
})