我试图找到一种模式,用于将事件回调从库包装到RxJS Observable。
我正在使用寄存器库处理此类事件:
const someHandler = (args) => {}`;
const resultCallback = (result) => {}`;
Library.addHandler('SOME_EVENT', someHandler, resultCallback);
Library.removeHandler('SOME_EVENT', someHandler, resultCallback);
resultCallback
是一个回调,如果处理程序已成功注册,则返回。
理想情况下,我想将处理程序作为函数的参数传入,并发出结果。
我不知道如何从此函数中发出处理程序的值,同时还维护要删除的对处理程序的对象引用。
addEventHandlerObservable<T>(handler: any): Observable<T> {
return new Observale(observer => {
SomeLibrary.addHandler('SOME_EVENT', handler,
(result) => {
// was registered successfully?
if(result.failed) {
observer.error();
observer.complete();
}
});
});
}
答案 0 :(得分:2)
rxjs已经为您做到了,fromEventPattern
可以观察到。
const resultCallback = (result) => {}; // not hyper clear on the point of this
const events$ = fromEventPattern(
(handler) => Library.addHandler('SOME_EVENT', handler, resultCallback),
(handler) => Library.removeHandler('SOME_EVENT', handler, resultCallback);
);
您不会在此处“传递”处理程序。您的订阅是您的处理程序:
events$.subscribe((val) => someHandler(val));