1 import { isArray } from './util/isArray';
2 import { isObject } from './util/isObject';
3 import { isFunction } from './util/isFunction';
4 import { UnsubscriptionError } from './util/UnsubscriptionError';
5 import { SubscriptionLike, TeardownLogic } from './types';
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.
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.
19 export class Subscription implements SubscriptionLike {
21 public static EMPTY: Subscription = (function(empty: any) {
24 }(new Subscription()));
27 * A flag to indicate whether this Subscription has already been unsubscribed.
30 public closed: boolean = false;
33 protected _parentOrParents: Subscription | Subscription[] = null;
35 private _subscriptions: SubscriptionLike[] = null;
38 * @param {function(): void} [unsubscribe] A function describing how to
39 * perform the disposal of resources when the `unsubscribe` method is called.
41 constructor(unsubscribe?: () => void) {
43 (this as any)._ctorUnsubscribe = true;
44 (this as any)._unsubscribe = unsubscribe;
49 * Disposes the resources held by the subscription. May, for instance, cancel
50 * an ongoing Observable execution or cancel any other type of work that
51 * started when the Subscription was created.
61 let { _parentOrParents, _ctorUnsubscribe, _unsubscribe, _subscriptions } = (this as any);
64 this._parentOrParents = 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;
69 if (_parentOrParents instanceof Subscription) {
70 _parentOrParents.remove(this);
71 } else if (_parentOrParents !== null) {
72 for (let index = 0; index < _parentOrParents.length; ++index) {
73 const parent = _parentOrParents[index];
78 if (isFunction(_unsubscribe)) {
79 // It's only possible to null _unsubscribe - to release the reference to
80 // any teardown function passed in the constructor - if the property was
81 // actually assigned in the constructor, as there are some classes that
82 // are derived from Subscriber (which derives from Subscription) that
83 // implement an _unsubscribe method as a mechanism for obtaining
84 // unsubscription notifications and some of those subscribers are
85 // recycled. Also, in some of those subscribers, _unsubscribe switches
86 // from a prototype method to an instance property - see notifyNext in
87 // RetryWhenSubscriber.
88 if (_ctorUnsubscribe) {
89 (this as any)._unsubscribe = undefined;
92 _unsubscribe.call(this);
94 errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
98 if (isArray(_subscriptions)) {
100 let len = _subscriptions.length;
102 while (++index < len) {
103 const sub = _subscriptions[index];
108 errors = errors || [];
109 if (e instanceof UnsubscriptionError) {
110 errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
120 throw new UnsubscriptionError(errors);
125 * Adds a tear down to be called during the unsubscribe() of this
126 * Subscription. Can also be used to add a child subscription.
128 * If the tear down being added is a subscription that is already
129 * unsubscribed, is the same reference `add` is being called on, or is
130 * `Subscription.EMPTY`, it will not be added.
132 * If this subscription is already in an `closed` state, the passed
133 * tear down logic will be executed immediately.
135 * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.
137 * @param {TeardownLogic} teardown The additional logic to execute on
139 * @return {Subscription} Returns the Subscription used or created to be
140 * added to the inner subscriptions list. This Subscription can be used with
141 * `remove()` to remove the passed teardown logic from the inner subscriptions
144 add(teardown: TeardownLogic): Subscription {
145 let subscription = (<Subscription>teardown);
148 return Subscription.EMPTY;
151 switch (typeof teardown) {
153 subscription = new Subscription(<(() => void)>teardown);
155 if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
156 // This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.
158 } else if (this.closed) {
159 subscription.unsubscribe();
161 } else if (!(subscription instanceof Subscription)) {
162 const tmp = subscription;
163 subscription = new Subscription();
164 subscription._subscriptions = [tmp];
168 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
172 // Add `this` as parent of `subscription` if that's not already the case.
173 let { _parentOrParents } = subscription;
174 if (_parentOrParents === null) {
175 // If we don't have a parent, then set `subscription._parents` to
176 // the `this`, which is the common case that we optimize for.
177 subscription._parentOrParents = this;
178 } else if (_parentOrParents instanceof Subscription) {
179 if (_parentOrParents === this) {
180 // The `subscription` already has `this` as a parent.
183 // If there's already one parent, but not multiple, allocate an
184 // Array to store the rest of the parent Subscriptions.
185 subscription._parentOrParents = [_parentOrParents, this];
186 } else if (_parentOrParents.indexOf(this) === -1) {
187 // Only add `this` to the _parentOrParents list if it's not already there.
188 _parentOrParents.push(this);
190 // The `subscription` already has `this` as a parent.
194 // Optimize for the common case when adding the first subscription.
195 const subscriptions = this._subscriptions;
196 if (subscriptions === null) {
197 this._subscriptions = [subscription];
199 subscriptions.push(subscription);
206 * Removes a Subscription from the internal list of subscriptions that will
207 * unsubscribe during the unsubscribe process of this Subscription.
208 * @param {Subscription} subscription The subscription to remove.
211 remove(subscription: Subscription): void {
212 const subscriptions = this._subscriptions;
214 const subscriptionIndex = subscriptions.indexOf(subscription);
215 if (subscriptionIndex !== -1) {
216 subscriptions.splice(subscriptionIndex, 1);
222 function flattenUnsubscriptionErrors(errors: any[]) {
223 return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);