'Chaining observables in javascript with or without merge map

I have the following functions:

  private findPanel(serviceId: string): Observable<Panel> {
    return this.panelService.getActivePanels().pipe(map(activePanels => activePanels.find(panel => panel.serviceId === serviceId)))
  }

  private createPanel(serviceId: string): Observable<Panel> {
   return this.panelService.addActiveFromService(serviceId);
  }

I want to chain them the following way: Get the Panel from findPanel, if it is undefined, call createPanel and get the Panel it returns, I don't know how I would be able to do this though. I read about mergeMap but did't manage to use it, could you help me with this one?



Solution 1:[1]

This chain should give you the panel object whether it is found or not. this.findPanel() will return undefined if not found, and in that case return a this.createPanel() inside mergeMap should do the job

this.findPanel(someid)
.pipe(mergeMap(found=>found?of(found):this.createPanel(someid)))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fan Cheung