首页 文章

Angular&RX:改进了订阅收集

提问于
浏览
4

Update

找到解决方案后,我根据接受的答案写了一个小助手ng2-rx-collector,使其更容易使用 . 希望它可以帮助一个人一次又一次地面对同样的问题 .

Original question

假设我们在hot observables上有一个包含两个订阅的组件 . 我们在 ngOnInit 中订阅它们并在 ngOnDestroy 中取消订阅以避免内存泄漏/意外行为:

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

我喜欢Rx,但每次我需要遵循这个时,我真的想要自杀:

  • 为每个订阅创建一个私人订阅属性

  • 将此属性分配给订阅(这看起来很丑陋,因为真正的逻辑转到了右侧)

  • 取消订阅destroy上的每个订阅

有没有办法改善这个?

例如 . 在RxSwift中他们有 DisposeBag 以便改进过程,翻译成打字稿将是:

private let bag = DisposeBag();

...

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

然后只破坏它一次 . 问题是我找不到任何类似的 Subscription 功能 .

任何想法/提示都会受到热烈欢迎 .

2 回答

  • 5

    你可以这样做:

    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();
    }
    
  • 2

    你所描述的曾经被称为RxJS 4中的“一次性用品”(如果我错了,请纠正我)或RxPHP . 在RxJS 5中,这称为订阅,但目的完全相同 .

    在以下示例中,我有两个源Observable . 我用一个 Subscription 对象包装他们的unsubscribe调用,该对象在调用 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);
    

    类似地,我也可以从 source1.subscribe 获取第一个 Subscription 并添加另一个 Subscription ,它将使用 add() 方法与其自己的 unsubscribe() 调用一起调用:

    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

相关问题