0

I want to return a boolean from an observable but the return line is executed before the subscribe. How can I do to return the boolean ?

private isLowResolution (file: File): boolean {
    this.getImageUri(file).pipe(
      mergeMap((imageUri: string) => this.readImage(imageUri)),
      mergeMap((image: HTMLImageElement) => of(this.minWidth > image.naturalWidth || this.minHeight > image.naturalHeight))
    ).subscribe(
      (isLow: boolean) => {
        this.isLow$.next(isLow);
      }
    );
    return this.isLow$.getValue();
  }

I looked at this How do I return the response from an Observable/http/async call in angular? and it don't answer to my question because I can't put the return into the subscribe. If I do that isLowResolution don't return the boolean anymore and I have and error

Ursule Maffo
  • 113
  • 1
  • 1
  • 6
  • Thanks for your response. No it's don't answer to my question, I can't put the return into the subscribe. Because if I do that `isLowResolution` don't return the boolean anymore and I have and error – Ursule Maffo May 09 '21 at 14:20
  • 1
    Well you really should subscribe where you actually need that value and not subscribe in `isLowResolution`. Also seems that `isLow$` is some kind of `Subject`, why don't you subscribe to that, as you are calling `next` on it? – AT82 May 09 '21 at 14:31
  • I am not sure what ````this.isLow$.getValue()```` will return but, since ````isLow$```` is a Behavior Subject or a Subject (assuming that because you are using .next() method), try this and see if it works: ````private isLowResolution(file: File): Observable {}```` – Srikar Phani Kumar M May 10 '21 at 14:04

1 Answers1

0

What you need to understand (and others have hinted at in their comments) is that Observables are asynchronous, somewhat like Promises in JavaScript or Futures in Scala.

An Observable is an object that will return a value (or an error) at some time in the future.

So, you simply can't use an Observable synchronously like you are asking.

But...JavaScript does support "waiting" for a Promise to resolve, so you can convert the Observable to a Promise, and then use async/await to do what you want.

Take a look at the accepted answer to How can I `await` on an Rx Observable? for an example.

I suggest that you try to do what you want asynchronously instead, since making this call pseudo-synchronous with "await" will likely lock up your UI while you are waiting for the response.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67