Search code examples
angularrxjsobservable

wait for value from observable


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 ...
}

Solution

  • 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 ...
      })
    }