Properly using bindCallback with RXJS6 and DWR

1.5k views Asked by At

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.

2

There are 2 answers

0
a better oliver On BEST ANSWER

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.

1
Picci On

From bindCallback documentation

The input is a function func with some parameters, the last parameter must be a callback function that func calls when it is done.

If I understand correctly your code

bindCallback(func, mappingFunction)

func is actually Foo.someFunction.

If I look at Foo.someFunction this is not a function with a callback function as its last parameter, as it is required by bindCallback.

So I am wondering if this code has ever worked.