相关疑难解决方法(0)

Subject.complete()是否取消订阅所有听众?

我用这个方法构建了一个简单的确认对话服务(Angular 2):

confirm(body?: string, title?: string): Subject<void> {
    this.confirmation = new Subject<void>();
    // ... show dialog here... "are you sure?"
    return this.confirmation;
}

_onYesClicked() {
  // ... closing the dialog
  this.confirmation.next();
  this.confirmation.complete();
} 

_onNoClicked() {
  // ... closing the dialog
  this.confirmation.complete();
}
Run Code Online (Sandbox Code Playgroud)

用法:

confirmationService.confirm().subscribe(() => alert("CONFIRMED"));
Run Code Online (Sandbox Code Playgroud)

如果有人使用该服务,他会返回一个Subject(这是一个Observable),并且可以"订阅()".点击"是"时调用订阅,因此确认给出了...

这是正确的方法吗?更重要的是...将致电

this.confirmation.complete();
Run Code Online (Sandbox Code Playgroud)

取消订阅订阅的侦听器,从而防止任何延迟引用(内存泄漏)?

observable rxjs angular

30
推荐指数
1
解决办法
1万
查看次数

rxjs科目应该在课堂上公开吗?

假设我有两个类,你可以观察一些可观察的类.

第一个例子,公共主题:

class EventsPub {
   public readonly onEnd = new Subject<void>();
}
Run Code Online (Sandbox Code Playgroud)

第二个例子,私人主题和注册方法:

class EventsPriv {
   private readonly endEvent = new Subject<void>();

   public onEnd(cb: () => void): Subscription {
       return this.endEvent.subscribe(cb);
   }
}
Run Code Online (Sandbox Code Playgroud)

第一个示例在某种程度上是不安全的,因为任何人都可以eventsPub.endEvent.next()从类外调用并引入副作用,但是,与示例2相比它允许管道,这是一个很大的优势,因为开发人员可以为ex.只注册第一个事件eventsPub.onEnd.pipe(first()).subscribe(cb).

第二个例子也允许一次性订阅,但需要更多的代码和丑陋的取消订阅.

const subscription = eventsPriv.onEnd(() => {
    // logic..
    subscription.unsubscribe()
});
Run Code Online (Sandbox Code Playgroud)

从您的角度来看,哪种方式最好?或者也许有更好的解决方案?

javascript reactive-programming rxjs rxjs5 angular

7
推荐指数
1
解决办法
708
查看次数