title: rxjs conditional nesting observables
body: <p>I have the following code which is working as intended:</p>
  
  
  
  <pre class="lang-ts prettyprint-override"><code>const sourceObservable = ... // irrelevant
  sourceObservable.subscribe(x =&gt; {
      doAnyway(x);
      if (x.Id) {             
          doSometing(x);
      } else {
          // id Not set, get default Id
          this.idService.getDefault().subscribe(id =&gt; {
              x.Id = id;                  
              doSometing(x);
          });
      }
  });
  </code></pre>
  
  <p>According to <a href="https://blog.strongbrew.io/rxjs-best-practices-in-angular/" rel="nofollow noreferrer">this article</a> nested subscribes are to avoid. Thats why i tried to refactor the above code, using pipes. I tried to realize the if-else operation with <a href="https://blog.rangle.io/rxjs-where-is-the-if-else-operator/" rel="nofollow noreferrer">this Method</a>, where filtering is used to create an observable branch for each option. And in the end they should be merged to subscribe.</p>
  
  <pre class="lang-ts prettyprint-override"><code>const obsShared = sourceObservable.pipe(
  tap(x =&gt; {
      doAnyway(x);
  }),
  share());
  
  const obsIdNotSet = obsShared.pipe(
      filter(x =&gt; !x.kennzahlId),
      merge(x =&gt; idService.getDefault().subscribe(id =&gt; {
              x.Id = id;
          // doSomething(x) will nomore be executed here
          })));
  
  // even though the true-part is empty I seem to need this to mergeing both options
  const obsIdSet = obsShared.pipe( 
      filter(x =&gt; !!x.Id),
      tap(() =&gt; {
          // doSomething(x) will nomore be executed here
      }));
  
  obsIdSet.pipe(merge(obsIdNotSet)).subscribe(x =&gt; {  
      // in case obsIdNotSet this will run with x.Id not set because x.Id will be set later
      doSometing(x);
  });
  </code></pre>
  
  <p>This code does compile and run without errors, only does it execute <code>doSomething(x)</code> before calling <code>idService.getDefault().....</code> and though it will be called without x.Id being set.</p>
  
  <p>What am i doing wrong?</p>