Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular & RX: improved subscription collection

Update

After the solution was found I wrote a small helper ng2-rx-collector based on the accepted answer to make it even easier to use. Hope it helps somebody facing the same problems again and again.

Original question

Assume we have a component with two subscriptions on hot observables. We subscribe to them in ngOnInit and unsubscribe in ngOnDestroy in order to avoid the memory leaks / unexpected behavior:

public ngOnInit() {
  this.s1 = o1.subscribe(console.debug.bind(console));
  this.s2 = o2.subscribe(console.debug.bind(console));
}

public ngOnDestroy() {
  this.s1.unsubscribe();
  this.s2.unsubscribe();
}

I love Rx, but I literally want to kill myself every time I need to follow this:

  1. Create a private subscription property for each subscription
  2. Assign this property to a subscription (this looks really ugly because the real logic goes to the right side)
  3. Unsubscribe from each subscription on destroy

Is there any way to improve this?

E.g. in RxSwift they have a DisposeBag in order to improve the process, translated to typescript would be:

private let bag = DisposeBag();

...

o1.subscribe(...).addDisposableTo(bag);

And then only destroying it only once. Problem is that I cannot find any similar Subscription function.

Any ideas / hints would be warmly welcomed.

like image 486
smnbbrv Avatar asked Mar 10 '23 11:03

smnbbrv


1 Answers

You can do this:

private teardown$ = new Subject<void>();

public ngOnInit() {
    o1.takeUntil(this.teardown$).subscribe(console.debug.bind(console));
    o2.takeUntil(this.teardown$).subscribe(console.debug.bind(console));
}

public ngOnDestroy() {
   this.teardown$.next();
}
like image 190
philipooo Avatar answered Mar 27 '23 08:03

philipooo