How to return value from function which has Observable subscription inside?

EDIT: updated code in order to reflect changes made to the way pipes work in more recent versions of RXJS. All operators (take in my example) are now wrapped into the pipe() operator.

I realize that this Question was quite a while ago and you surely have a proper solution by now, but for anyone looking for this I would suggest solving it with a Promise to keep the async pattern.

A more verbose version would be creating a new Promise:

function getValueFromObservable() {
    return new Promise(resolve=>{
        this.store.pipe(
           take(1) //useful if you need the data once and don't want to manually cancel the subscription again
         )
         .subscribe(
            (data:any) => {
                console.log(data);
                resolve(data);
         })
    })
}

On the receiving end you will then have “wait” for the promise to resolve with something like this:

getValueFromObservable()
   .then((data:any)=>{
   //... continue with anything depending on "data" after the Promise has resolved
})

A slimmer solution would be using RxJS’ .toPromise() instead:

function getValueFromObservable() {
    return this.store.pipe(take(1))
       .toPromise()   
}

The receiving side stays the same as above of course.

Leave a Comment