6
votes

I need a little help with making a function return an observable. I have a function (let's call it mainFunction), that calls an async function (let's call it getAsyncWithCallback) and executes a callback. Part of the callback is an async call that returns an observable (let's call it getData).

getAsyncWithCallback is part of a library and I cannot change it.

This is what I have:

mainFunction(){
    getAsyncWithCallback(() => {
        let myObservable = getData();
    });
}

This is what I want to do:

mainFunction().subscribe((data) => { 
    // data is the data from getData()
});

What is the best way to achieve this, and chain in the error and completion form the inner?

2
If they don't return myObservable (or assign it somewhere), I don't think there's much you can do...acdcjunior
I'm pretty sure you can use promise and convert it into observable. I don't have IDE atm to provide you an example.MistyK
The callback is code I can change. I defined myObservable in there.Grey

2 Answers

2
votes

my solution:

mainFunction(): Observable<any> {

    return Rx.Observable.create(observer => {
        getAsyncWithCallback((): void => {
            getData().subscribe(observer);
        })
    })
}

mainFunction().subscribe((data) => {
    console.log(data);
})); 
0
votes

You will want to return an Observable from mainFunction.

If getData returns some other type of object that is not an Observable, you will construct your own Observable with Observable.create:

function mainFunction() {
  return Observable.create((obs) => {
    getAsyncWithCallback(() => {
      getData()
        .subscribe((data) => { obs.next(data); })
        .catch((err) => { obs.error(err) });
    });
  });
}

mainFunction().subscribe(data => console.log(data));

From the docs:

create converts an onSubscription function to an actual Observable. Whenever someone subscribes to that Observable, the function will be called with an Observer instance as a first and only parameter

Calling next with a value will emit that value to the observer.

Most of the times you should not need to use create, because existing operators allow you to create an Observable for most of the use cases. That being said, create is low-level mechanism allowing you to create any Observable, if you have very specific needs.

There's also Observable.from which will create Observables from arrays, array-like objects, iterators, Observable-like objects and Promises.