Search code examples
typescriptcallbackrxjsdwr

Properly using bindCallback with RXJS6 and DWR


I'm currently using bindCallback the following (now deprecated) way:

const someMapping = (data) => { return { ... }};

public someCall(id) {
  // Foo.someFunction is function with callbacks
  return this.toObservable(Foo.someFunction, someMapping, id);
}

private toObservable(func, mappingFunction, ...args: any[]) {
  return bindCallback(func, mappingFunction)(...args);
} 

Other than this being deprecated, I have another issue. If I call the someFunction manually:

var callFn = function(data) {...}
var warnFn = function(data) {...}
var errFn = function(data) {...}
Foo.someFunction(id, {callback: callFn, warningHandler: warnFn, errorHandler: errFn})

It will throw success, warnings and errors correctly. I didn't create this DWR callback function (there are many of them), and I can't change them. Documentation isn't helping enough.

How can I modify this to handle all three (success, warning, error) callbacks and return as observables? Warning and error can both throw an error.


Solution

  • The best option is to create your own observable.

    public someCall(id) {
      return new Observable(observer => {
                             Foo.someFunction(id,
                               {
                                callback: value => {
                                                     observer.next(value);
                                                     observer.complete();
                                                   },
                                warningHandler: warn => observer.error(warn),
                                errorHandler: error => observer.error(error)
                              });
    
                            });
    

    It's similar to calling someFunction manually but emits to a stream.