I have the following code:
// code is in a state class for ngxs
const someObject = ctx.getState().someObject;
const sourceArray: SomeType[] = [/* content */];
return from(sourceArray).pipe(
tap((arrayElem) => ctx.patchState({currentElem: arrayElem})),
switchMap((arrayElem) => {
return this.someService.someMethod(arrayElem);
}),
catchError((err) => {
return of(err);
}),
finalize(() => {
console.log("Test"); // Never called
})
);
someMethod(request) {
return this.someClientAsync().pipe(
switchMap((theClient) => {
return new Observable<ReturnType>(subscriber => {
theClient.makeCall(request, (err, data) => {
if (err) {
subscriber.error(err)
}
subscriber.next(data);
});
});
})
);
}
The problem is: the code in the switchMap operator is called correctly, for every array element, but the finalize method is never called.
It may be due to the code in someMethod: There, I had to wrap code that uses callbacks into an observable. The methods that the object returned by someClientAsync() has this callback-style API.
But I am not sure. The way I wrapped the callback into the observable works for other methods in that service. And as I wrote, switchMap is actually called n times, n being the array length.
Thanks for any help!
EDIT
Thanks all for the posts! Got some really nice information here I wasn't aware of.
I think my problem is the way I wrap the callback-style API into the observable in someMethod in the service.
The actual API I need to use looks like this:
someClient.doAction(params, (data, err) => {
// callback
});
and I would like to convert this into an observable.
I think I need to go with at @martin' answer unless someone thinks it's not the way to do it.