Home > Blockchain >  wait for value from observable
wait for value from observable

Time:07-26

I want to get the value of an observable, and return it from a synchronous function.

If the code was in html, I could use {{singleEvents$ | async}} .

I don't know of something similar in TS.

I know it's possible to subscribe for an observable to get it's values, but this is still asynchronous. I want the next line of code to only execute after I got a (single) value from the observable, and for the flow to continue synchronously afterwards.

Thanks,

P.S The reason I want this is that Im running different flows of the code depending on the result. I'd need to make everything asynchronous otherwise.

Edit: this is how the code looks like -

function ReturnVal() {
  let obs : Observable<boolean> = getFromHttp();
  return ... unsure what to write here ...;
}

function DoStuff () {
  ... lots of logic ...
  if ReturnVal() {
     return;
  }
  ... lots of logic ...
}

CodePudding user response:

You can use pipe operators.

ngOnInit() {
  singleEvents$.pipe(
    take(1), // this ensures only one event fires and automatically unsubscribes after code runs
    // tap(console.log) // for debugging
  ).subscribe((singleEvents: ISingleEvent[]) => {
    // do something with singleEvents
  })
}

Edit

One way to do something similar to your example

returnVal$(): Observable<boolean> {
  let obs : Observable<boolean> = getFromHttp();
  return obs
}

doStuff () {
  ... lots of logic ...

  this.returnVal$().pipe(
    take(1),
  ).subscribe(returnVal => {
     if (returnVal) {
       return;
    }
    ... lots of logic ...
  })
}

CodePudding user response:

You can not simply write some synchronous function to return a value of some observable. The correct answer to your question depends on the situation, but I would suggest looking into withLatestFrom, combineLatest, or simply subscribing with take(1). Either way your code will be reacting to an observable, it will be asynchronous.

You can use lastValueFrom or firstValueFrom and await those, but read the documentation to know what to expect either when the observable does not complete or when the observable is a ReplaySubject

  • Related