0
votes

Is there a way to await for the first value returned from a subscribe call?

For example, in the following:

async getValue(...) {
  myObs$ = ...
  let val = await myObs$.pipe(first()).toPromise()
  myObs$.subscribe(val => {
    this.value = val
  })
  return val
}

The async function will return a Promise of val, but I also want to subscribe and get a data member value that will be updated whenever the observable myObs$ emits a new value.

My question: is there away to return a Promise without calling the line with the first() call and just wait for the first time I get the result in subscribe?

1
You can just switch the order and use await myObs$.pipe(first()).toPromise() after you subscribe. - martin
Calling toPromise effects an implicit subscription to the observable upon which it's called. - cartant
I should say the code above works, but the question I have is related to the fact that I am getting the value twice, once for the first() line and then within the subscribe. I am trying to determine if its possible to wait on the subscription and then return it, but ALSO continue to update the value for any future updates. - user1369641
Why do you want to wait for the observable to emit a value? You could just call a function when you recieve a value in subscribe for the first time. This would be the reactive way to do it. - frido
I need the value synchronously and also want to cache the value (and keep it updated) so I don't have to go to the server again. There only real issue is that I have to go to the server twice in the above code, and was hoping to avoid that extra call. - user1369641

1 Answers

0
votes

There's no real reason here that this method needs to be async as the caller will have to await it or use .then() regardless. You could simply rewrite it as:

getValue(...) {
  myObs$ = ...
  myObs$.subscribe(val => {
    this.value = val
  })
  return myObs$.pipe(first()).toPromise()
}

This will keep your internal subscription around and allow it to keep receiving values while the caller of getValue will receive a Promise of the first emitted value.