Reputation: 1846
I'm trying to find a pattern for wrapping an event callback from a library to an RxJS Observable.
The library I'm using registers handlers for events like this:
const someHandler = (args) => {}`;
const resultCallback = (result) => {}`;
Library.addHandler('SOME_EVENT', someHandler, resultCallback);
Library.removeHandler('SOME_EVENT', someHandler, resultCallback);
The resultCallback
is a callback that returns if the handler was registered successfully.
Ideally, I would like to pass the handler in as a parameter of the function, and emit it's result.
I don't know how I can emit the value of the handler from this function, while also maintaining an object reference to the handler for removal.
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();
}
});
});
}
Upvotes: 1
Views: 895
Reputation: 29325
rxjs already did this for you, with the fromEventPattern
observable.
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);
);
you don't "pass in" the handler here. Your subscribe IS your handler:
events$.subscribe((val) => someHandler(val));
Upvotes: 2