Дарья
Дарья

Reputation: 167

How to use promises to get an Observable?

I have a class with an Observable in it. I want to create second Observable that will be generated by the value of the first observable and the response of the HTTP-request. I want to regenerate value of the second Observalble on every change in the first Observable.

I need to get Observable<number> in returning type. I tried to do it with map, switchMap, fromPromise. In some cases the returning type of the second Observable became Observable<Observable<number>> (when I used map), in some cases typescript hinted me that the returning type should be ObservableInput<number>.

Help me to understand how to correctly use promises in rxjs!

function someHTTPRequest(): Promise<number> {
}

class MyClass {
  firstObs$: Observable<Array<string>>;
  
  get secondObs$(): Observable<number> {
    return firstObs$.pipe(
     switchMap((items: Array<string>) => fromPromise(someHTTPRequest(items)))
    )
  }
}

Upvotes: 1

Views: 45

Answers (1)

I assume you mean pass the string items to the someHTTPrequest

function someHTTPRequest(items:Array<string>): Promise<number> {
}

class MyClass {
  firstObs$: Observable<Array<string>>;
  
  get secondObs$(): Observable<number> {
    return firstObs$.pipe(
     switchMap((items: Array<string>) => fromPromise(someHTTPRequest(items)))
    )
  }
}

When inside a mergeMap or switchmap you can return promises, so you do not need to use from.

class MyClass {
  firstObs$: Observable<Array<string>>;
  
  get secondObs$(): Observable<number> {
    return this.firstObs$.pipe(
     switchMap((items: Array<string>) => { 
         return someHTTPRequest(items));
    })
  }
}

EDIT: based on the comment that the items array would be undefined is due to it starts the observable with no values, you could turn it into a behavior subject and give it an initial value if that is not expected you could do this.

class MyClass {
  firstObs$: Observable<Array<string>>;
  
  get secondObs$(): Observable<number> {
    return this.firstObs$.pipe(
     switchMap((items: Array<string>) => { 
         if(items)
              return someHTTPRequest(items));
         return EMPTY;
    })
  }
}

Upvotes: 1

Related Questions