Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs, How to link up callback method to Observable?

Tags:

rxjs

I need to link up a call-back method to the 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 a contentURI, and I need to call the this.$window.FilePath.resolveNativePath method which is using the call-back . and it should return the absolute path to next map method.

How can I link up the call-back method between returning promise and parsing map method?

enter image description here

like image 858
Expert wanna be Avatar asked Oct 18 '22 14:10

Expert wanna be


1 Answers

You can use bindCallback to create an observable for the 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've used an arrow function so that argument types are explicit and so that resolveNativePath is called on this.$window.FilePath.

I've not used Function.prototype.bind, as it returns any and really messes with TypeScript's inferring of the types for the bindCallback function.

The above answer uses RxJS 5. However, the additional information that you've added to your question shows that you are using version 4. In that version, the function is named fromCallback.

like image 86
cartant Avatar answered Oct 21 '22 00:10

cartant