Search code examples
angularrxjsrxjs6rxjs-observables

Merging an Observable and Promise to an Object


How do I merge two function returns (one returns a promise, one returns a object) from an Observables? How do I chain the results? What is the proper way to do this?

functionReturnObservable(
        element: SomeInterface,
    ): Observable<Interface> {
        return this.someService.fn2ReturnObservable().pipe(
            map((result) => {
                // the promise function needs to merge with the funcObject
                const updatedElement= from(this.fnPromise(element))
                return this.funObject(updatedElement, result);
            }),
        );
    }

funcObject(
        updatedElement: Readonly<Interface>,
        listItems: IInterface[],
    ): IObject {
        // returns a revised Object
        return updatedObjects;
    }

async fnPromise(elements: IElements): Promise<SomeInterface> {
        // ... some other stuff 
        let result;
        result.Name = "John"
        if( elements.References) {
            await this.otherService
            .lookup(elements.References)
            .then((result) => {
                result.Secret= result;
            });
        }
        return result;
    }

Solution

  • use a higher order observable:

    functionReturnObservable(
        element: SomeInterface,
    ): Observable<Interface> {
        return this.someService.fn2ReturnObservable().pipe(
            switchMap((result) => {
                // switchMap will subscribe to inner observable, use map to combine results
                return from(this.fnPromise(element)).pipe(
                  map(updatedElement => this.funObject(updatedElement, result)));
            }),
        );
    }
    

    this might break a bit trying to use async / await, it doesn't mix well with observables. If it's still broken, remove the async / await stuff and just return promises.