Subscription.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import { isArray } from './util/isArray';
  2. import { isObject } from './util/isObject';
  3. import { isFunction } from './util/isFunction';
  4. import { tryCatch } from './util/tryCatch';
  5. import { errorObject } from './util/errorObject';
  6. import { UnsubscriptionError } from './util/UnsubscriptionError';
  7. /**
  8. * Represents a disposable resource, such as the execution of an Observable. A
  9. * Subscription has one important method, `unsubscribe`, that takes no argument
  10. * and just disposes the resource held by the subscription.
  11. *
  12. * Additionally, subscriptions may be grouped together through the `add()`
  13. * method, which will attach a child Subscription to the current Subscription.
  14. * When a Subscription is unsubscribed, all its children (and its grandchildren)
  15. * will be unsubscribed as well.
  16. *
  17. * @class Subscription
  18. */
  19. export class Subscription {
  20. /**
  21. * @param {function(): void} [unsubscribe] A function describing how to
  22. * perform the disposal of resources when the `unsubscribe` method is called.
  23. */
  24. constructor(unsubscribe) {
  25. /**
  26. * A flag to indicate whether this Subscription has already been unsubscribed.
  27. * @type {boolean}
  28. */
  29. this.closed = false;
  30. this._parent = null;
  31. this._parents = null;
  32. this._subscriptions = null;
  33. if (unsubscribe) {
  34. this._unsubscribe = unsubscribe;
  35. }
  36. }
  37. /**
  38. * Disposes the resources held by the subscription. May, for instance, cancel
  39. * an ongoing Observable execution or cancel any other type of work that
  40. * started when the Subscription was created.
  41. * @return {void}
  42. */
  43. unsubscribe() {
  44. let hasErrors = false;
  45. let errors;
  46. if (this.closed) {
  47. return;
  48. }
  49. let { _parent, _parents, _unsubscribe, _subscriptions } = this;
  50. this.closed = true;
  51. this._parent = null;
  52. this._parents = null;
  53. // null out _subscriptions first so any child subscriptions that attempt
  54. // to remove themselves from this subscription will noop
  55. this._subscriptions = null;
  56. let index = -1;
  57. let len = _parents ? _parents.length : 0;
  58. // if this._parent is null, then so is this._parents, and we
  59. // don't have to remove ourselves from any parent subscriptions.
  60. while (_parent) {
  61. _parent.remove(this);
  62. // if this._parents is null or index >= len,
  63. // then _parent is set to null, and the loop exits
  64. _parent = ++index < len && _parents[index] || null;
  65. }
  66. if (isFunction(_unsubscribe)) {
  67. let trial = tryCatch(_unsubscribe).call(this);
  68. if (trial === errorObject) {
  69. hasErrors = true;
  70. errors = errors || (errorObject.e instanceof UnsubscriptionError ?
  71. flattenUnsubscriptionErrors(errorObject.e.errors) : [errorObject.e]);
  72. }
  73. }
  74. if (isArray(_subscriptions)) {
  75. index = -1;
  76. len = _subscriptions.length;
  77. while (++index < len) {
  78. const sub = _subscriptions[index];
  79. if (isObject(sub)) {
  80. let trial = tryCatch(sub.unsubscribe).call(sub);
  81. if (trial === errorObject) {
  82. hasErrors = true;
  83. errors = errors || [];
  84. let err = errorObject.e;
  85. if (err instanceof UnsubscriptionError) {
  86. errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
  87. }
  88. else {
  89. errors.push(err);
  90. }
  91. }
  92. }
  93. }
  94. }
  95. if (hasErrors) {
  96. throw new UnsubscriptionError(errors);
  97. }
  98. }
  99. /**
  100. * Adds a tear down to be called during the unsubscribe() of this
  101. * Subscription.
  102. *
  103. * If the tear down being added is a subscription that is already
  104. * unsubscribed, is the same reference `add` is being called on, or is
  105. * `Subscription.EMPTY`, it will not be added.
  106. *
  107. * If this subscription is already in an `closed` state, the passed
  108. * tear down logic will be executed immediately.
  109. *
  110. * @param {TeardownLogic} teardown The additional logic to execute on
  111. * teardown.
  112. * @return {Subscription} Returns the Subscription used or created to be
  113. * added to the inner subscriptions list. This Subscription can be used with
  114. * `remove()` to remove the passed teardown logic from the inner subscriptions
  115. * list.
  116. */
  117. add(teardown) {
  118. if (!teardown || (teardown === Subscription.EMPTY)) {
  119. return Subscription.EMPTY;
  120. }
  121. if (teardown === this) {
  122. return this;
  123. }
  124. let subscription = teardown;
  125. switch (typeof teardown) {
  126. case 'function':
  127. subscription = new Subscription(teardown);
  128. case 'object':
  129. if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
  130. return subscription;
  131. }
  132. else if (this.closed) {
  133. subscription.unsubscribe();
  134. return subscription;
  135. }
  136. else if (typeof subscription._addParent !== 'function' /* quack quack */) {
  137. const tmp = subscription;
  138. subscription = new Subscription();
  139. subscription._subscriptions = [tmp];
  140. }
  141. break;
  142. default:
  143. throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
  144. }
  145. const subscriptions = this._subscriptions || (this._subscriptions = []);
  146. subscriptions.push(subscription);
  147. subscription._addParent(this);
  148. return subscription;
  149. }
  150. /**
  151. * Removes a Subscription from the internal list of subscriptions that will
  152. * unsubscribe during the unsubscribe process of this Subscription.
  153. * @param {Subscription} subscription The subscription to remove.
  154. * @return {void}
  155. */
  156. remove(subscription) {
  157. const subscriptions = this._subscriptions;
  158. if (subscriptions) {
  159. const subscriptionIndex = subscriptions.indexOf(subscription);
  160. if (subscriptionIndex !== -1) {
  161. subscriptions.splice(subscriptionIndex, 1);
  162. }
  163. }
  164. }
  165. _addParent(parent) {
  166. let { _parent, _parents } = this;
  167. if (!_parent || _parent === parent) {
  168. // If we don't have a parent, or the new parent is the same as the
  169. // current parent, then set this._parent to the new parent.
  170. this._parent = parent;
  171. }
  172. else if (!_parents) {
  173. // If there's already one parent, but not multiple, allocate an Array to
  174. // store the rest of the parent Subscriptions.
  175. this._parents = [parent];
  176. }
  177. else if (_parents.indexOf(parent) === -1) {
  178. // Only add the new parent to the _parents list if it's not already there.
  179. _parents.push(parent);
  180. }
  181. }
  182. }
  183. Subscription.EMPTY = (function (empty) {
  184. empty.closed = true;
  185. return empty;
  186. }(new Subscription()));
  187. function flattenUnsubscriptionErrors(errors) {
  188. return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);
  189. }
  190. //# sourceMappingURL=Subscription.js.map