我试图用RXJS Observables包装一个基于事件的API,但是我不知道取消订阅后如何清理自己。
这几乎就是我如何将订阅与Observable和基于事件的API同步的方法:
interface SomeEventService{
registerListener(messageName: string, messageContent: Something): Listener;
unregisterListener(listener: Listener);
}
class MyWrapper {
private eventService: SomeEventService;
streamOfSomething$(): Observable<Something> {
return Observable.create((observer: Observer<Something>) => {
// Create a listener, and relay events to the Observable
const listener = this.eventService.registerListener("something", something => {
observer.next(something);
})
// Now what?
})
}
}
这里的问题是,将来我想打电话给eventService.unregisterListener
,例如streamOfSomething$
的使用者取消订阅流时。
问题:我该怎么做?据我所知,没有事件或回调可以在退订发生后在observer
上运行代码。
答案 0 :(得分:1)
class MyWrapper {
private eventService: SomeEventService;
streamOfSomething$(): Observable<Something> {
return Observable.create((observer: Observer<Something>) => {
// Create a listener, and relay events to the Observable
const listener = this.eventService.registerListener("something", something => {
observer.next(something);
})
// Now what?
return () => { this.eventService.unRegisterListener(); };
})
}
}
当用户调用unsubscribe()时,将调用您将返回的函数