Andrea Koutifaris
1 min readMar 20, 2019

--

Let’s refactor a bit your example and move towards the subscription.add() solution.

this.subs[this.subs.length] = this.myObs.subscribe();

may be re-written into

this.subs.push(this.myObs.subscribe());

then

If( this.subs.length > 0 ) {

this.subs.forEach(sub => sub.unsubscribe() );

}

may be shortened into (no need for the if statement):

this.subs.forEach(sub => sub.unsubscribe() )

Now, there is an interesting design pattern, called Composite. It happens that a Subscription is a composite. This means that using a subscription you can avoid the .foreach and just call unsubscribe().

So your example can be simplified further more:

this.subs.add(this.myObs.subscribe());

and in the ngOnDestroy method:

this.subs.unsubscribe()

Where this.subs is now:

subs = new Subscription();

--

--

Andrea Koutifaris
Andrea Koutifaris

No responses yet