I know you don't have to unsubscribe from a promise, but what if i use the from()
rxjs operator to turn that promise into a observable and subscribe to it like so:
from(image.decode()).pipe(catchError(error => of('failed to load image')))
.subscribe(s => this.imageLoading = false)
I've looked in the official documentation for from()
and on different tutorial sites but none of them mention anything about unsubscribing. Can anyone please clarify? Thank you
When you have from(promise)
, I'd say you don't have to unsubscribe .
Here's how from
is defined:
export function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {
if (!scheduler) {
if (input instanceof Observable) {
return input;
}
// Reached when having `from(promise)`
return new Observable<T>(subscribeTo(input));
} else {
return scheduled(input, scheduler);
}
}
subscribeTo
is defined as follows:
/* ... */
else if (isPromise(result)) {
return subscribeToPromise(result);
}
/* ... */
And finally, subscribeToPromise
:
export const subscribeToPromise = <T>(promise: PromiseLike<T>) => (subscriber: Subscriber<T>) => {
promise.then(
(value) => {
if (!subscriber.closed) {
subscriber.next(value);
subscriber.complete();
}
},
(err: any) => subscriber.error(err)
)
.then(null, hostReportError);
return subscriber;
};
As you can see, after the first emitted value, it will send a complete
notification, so there is no need to unsubscribe.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.