Angular & RX: Enhanced Subscription

Update

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

Original question

Suppose we have a component with two subscriptions to hot observables. We subscribe to them in ngOnInitand unsubscribe in ngOnDestroyto avoid 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 like Rx, but I literally want to kill myself every time I need to follow this:

  • Create a private subscription property for each subscription
  • Assign this property to a subscription (it looks really ugly, because the real logic goes in the right direction)

?

. RxSwift DisposeBag, , typescript:

private let bag = DisposeBag();

...

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

. , Subscription.

/ .

+4
2

:

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();
}
+5

, , "" RxJS 4 ( , ) RxPHP. RxJS 5 , .

Observables. Subscription, , unsubscribe().

var source1 = Observable.interval(250);
var source2 = Observable.interval(350);

let sub1 = source1.subscribe(val => console.log(val));
let sub2 = source2.subscribe(val => console.log(val));

let subscriptions = new Subscription(() => {
    sub1.unsubscribe();
    sub2.unsubscribe();
});

setTimeout(() => {
    subscriptions.unsubscribe();
}, 3000);

, Subscription source1.subscribe Subscription, unsubscribe(), add():

var source1 = Observable.interval(250);
var source2 = Observable.interval(350);

let subscriptions = source1.subscribe(val => console.log(val));
subscriptions.add(source2.subscribe(val => console.log(val)));

setTimeout(() => {
    subscriptions.unsubscribe();
}, 3000);

. : https://github.com/ReactiveX/rxjs/blob/master/src/Subscription.ts

+2

Source: https://habr.com/ru/post/1663080/


All Articles