简体   繁体   中英

RXJS6 - return an Observable from a Promise function which returns an Observable?

I have a method getData which returns an Observable<SupportingDocument> .
( code and return value can't be changed as it's an external API ).

  getData(): Observable<SupportingDocument> {
    return of(new SupportingDocument());
  }

When a user clicks a button , we actually show him a Modal page . When that modal is closed ( Promise api) - we should call getData() and return the value :

  public dialogShow(): Promise<Observable<SupportingDocument>> {
    return Promise.resolve(1).then(() => { //modal was closed
      return this.getData();
    })
  }

At the end , I should provide a method show() which should return the value(and errors) that returned from return this.getData(); ( shows()'s return value doesn't have to be an Observable , it can be a promise too ).

So I did this :

  public show(): Observable<SupportingDocument> {
    return new Observable<SupportingDocument>((obs) => {
      this.dialogShow().then((res: Observable<SupportingDocument>) => obs.next(res), (res) => obs.error(res));
    })
  }

Complete code :

//user starts here
public show(): Observable<SupportingDocument> {
    return new Observable<SupportingDocument>((obs) => {
      this.dialogShow().then((res: Observable<SupportingDocument>) => obs.next(res), (res) => obs.error(res));
    })
  }



  public dialogShow(): Promise<Observable<SupportingDocument>> {
    return Promise.resolve(1).then(() => {
      return this.getData();
    })
  }


  getData(): Observable<SupportingDocument> {
    return of(new SupportingDocument());

  }

Question

I think I've over-complicated such a simple task. More - I really don't like the new Observable constructor approach.

Can this problem be solved without using the observable constructor ( including error handling) solution ?

Full demo code

Why don't just wrap the Promise into an Observable (so that you can use all the operators an Observable can provide) , and then use a switchMap() ?

public dialogShow(): Observable<SupportingDocument> {
    return from(Promise.resolve(1)).pipe(switchMap(() => this.getData()));
}

Working StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM