Rxjs; How to associate a callback method with an observable?

I need to bind a callback method to an Observable chain.

private testMethod(): Rx.Observable<any> {
        const deferred = this.$q.defer();
        let promise = deferred.promise;

        this.$window.fileChooser.open((results: any) => {
            deferred.resolve(results);
        }, (error: any) => {
            this.Logger.log(error);
        });

        return this.rx.Observable.fromPromise(promise)
            .map((contentURI: string) => {
                // need to link call-back method
                this.$window.FilePath.resolveNativePath(contentURI, (absolutePath: any) => {
                    // need to pass absolutePath to next map method
                    return absolutePath;
                });
            })
            .map((fileEntry: any) => {
                let results = [];
                results.push({
                    fileEntry,
                    mimeType: 'image/jpeg'
                });
                return results;
            })
            .catch(this.ExceptionService.observableCatcher('error'));
}

from the promise, I can get the contentURI, and I need to call the this method . $ window.FilePath.resolveNativePath , which uses a callback. and it should return the absolute path to the next map method.

How can I link the callback method between the return promise and the parsing method of the card?

enter image description here

+4
source share
1 answer

You can use bindCallbackto create an observable for a callback:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/bindCallback';

...
.map((contentURI: string) => {
  const bound = Observable.bindCallback((
    path: string,
    callback: (result: string) => void
  ) => this.$window.FilePath.resolveNativePath(path, callback));
  return bound(contentURI);
})
...

I used the arrow function, so the argument types are explicit and therefore resolveNativePathcalled on this.$window.FilePath.

Function.prototype.bind, any TypeScript bindCallback.

RxJS 5. , , , 4. fromCallback.

+2

Source: https://habr.com/ru/post/1673661/


All Articles