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 export class Subscription {
6 constructor(unsubscribe) {
8 this._parentOrParents = null;
9 this._subscriptions = null;
11 this._unsubscribe = unsubscribe;
19 let { _parentOrParents, _unsubscribe, _subscriptions } = this;
21 this._parentOrParents = null;
22 this._subscriptions = null;
23 if (_parentOrParents instanceof Subscription) {
24 _parentOrParents.remove(this);
26 else if (_parentOrParents !== null) {
27 for (let index = 0; index < _parentOrParents.length; ++index) {
28 const parent = _parentOrParents[index];
32 if (isFunction(_unsubscribe)) {
34 _unsubscribe.call(this);
37 errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
40 if (isArray(_subscriptions)) {
42 let len = _subscriptions.length;
43 while (++index < len) {
44 const sub = _subscriptions[index];
50 errors = errors || [];
51 if (e instanceof UnsubscriptionError) {
52 errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
62 throw new UnsubscriptionError(errors);
66 let subscription = teardown;
68 return Subscription.EMPTY;
70 switch (typeof teardown) {
72 subscription = new Subscription(teardown);
74 if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
77 else if (this.closed) {
78 subscription.unsubscribe();
81 else if (!(subscription instanceof Subscription)) {
82 const tmp = subscription;
83 subscription = new Subscription();
84 subscription._subscriptions = [tmp];
88 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
91 let { _parentOrParents } = subscription;
92 if (_parentOrParents === null) {
93 subscription._parentOrParents = this;
95 else if (_parentOrParents instanceof Subscription) {
96 if (_parentOrParents === this) {
99 subscription._parentOrParents = [_parentOrParents, this];
101 else if (_parentOrParents.indexOf(this) === -1) {
102 _parentOrParents.push(this);
107 const subscriptions = this._subscriptions;
108 if (subscriptions === null) {
109 this._subscriptions = [subscription];
112 subscriptions.push(subscription);
116 remove(subscription) {
117 const subscriptions = this._subscriptions;
119 const subscriptionIndex = subscriptions.indexOf(subscription);
120 if (subscriptionIndex !== -1) {
121 subscriptions.splice(subscriptionIndex, 1);
126 Subscription.EMPTY = (function (empty) {
129 }(new Subscription()));
130 function flattenUnsubscriptionErrors(errors) {
131 return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);
133 //# sourceMappingURL=Subscription.js.map