fetch.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { __rest } from "tslib";
  2. import { createOperatorSubscriber } from '../../operators/OperatorSubscriber';
  3. import { Observable } from '../../Observable';
  4. import { innerFrom } from '../../observable/innerFrom';
  5. export function fromFetch(input, initWithSelector = {}) {
  6. const { selector } = initWithSelector, init = __rest(initWithSelector, ["selector"]);
  7. return new Observable((subscriber) => {
  8. const controller = new AbortController();
  9. const { signal } = controller;
  10. let abortable = true;
  11. const { signal: outerSignal } = init;
  12. if (outerSignal) {
  13. if (outerSignal.aborted) {
  14. controller.abort();
  15. }
  16. else {
  17. const outerSignalHandler = () => {
  18. if (!signal.aborted) {
  19. controller.abort();
  20. }
  21. };
  22. outerSignal.addEventListener('abort', outerSignalHandler);
  23. subscriber.add(() => outerSignal.removeEventListener('abort', outerSignalHandler));
  24. }
  25. }
  26. const perSubscriberInit = Object.assign(Object.assign({}, init), { signal });
  27. const handleError = (err) => {
  28. abortable = false;
  29. subscriber.error(err);
  30. };
  31. fetch(input, perSubscriberInit)
  32. .then((response) => {
  33. if (selector) {
  34. innerFrom(selector(response)).subscribe(createOperatorSubscriber(subscriber, undefined, () => {
  35. abortable = false;
  36. subscriber.complete();
  37. }, handleError));
  38. }
  39. else {
  40. abortable = false;
  41. subscriber.next(response);
  42. subscriber.complete();
  43. }
  44. })
  45. .catch(handleError);
  46. return () => {
  47. if (abortable) {
  48. controller.abort();
  49. }
  50. };
  51. });
  52. }
  53. //# sourceMappingURL=fetch.js.map