I have the following code which works intermittently. Sometimes the getCurrentPosition promise does not resolve in time, and undefined gets passed to the first switchMap in my pipe, which breaks everything of course.
Location Service:
// Get user location
public getUserLocation(): Observable<LocationModel> {
const options = {
enableHighAccuracy: true,
timeout: environment.userLocationTimeout
};
return from(Geolocation.getCurrentPosition(options)).pipe(
map((position) => {
const location = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
return location;
})
);
}
Subscriptions Page:
// Get Subscriptions
private getSubscriptions(): void {
this.locationService
.getUserLocation()
.pipe(
switchMap((location: LocationModel) => this.locationAddressService.getAddress(location)),
switchMap((address: AddressModel) => this.subscriptionsService.getSubscriptions(address)),
takeUntil(this.destroy$)
)
.subscribe((subscriptions) =>
this.zone.run(() => {
this.subscriptions = subscriptions;
})
);
}
I am expecting the from() to only return the LocationModel when the promise is resolved, but that doesn't seem to be what's happening. Am I using it incorrectly? How can I ensure that there is a LocationModel ready for the switchMap?
We are trying to stay away from promises as much as possible as they mess with our error logging, so are trying to use observables wherever we can.
Additionally, assuming the location is returned on time, I need to set the UI element inside the NgZone, if I don't then it takes a long time to update the UI after the subscriptions have been returned. I don't think this is the same issue however.