Subscription.ts 7.1 KB

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