title: RxJs: Prevent infinite loop
body: <p>Consider the following scenario:    </p>
  
  <pre><code>observerX =&gt; observableA &lt;= observerY =&gt; observableB &lt;= observerZ
  </code></pre>
  
  <ul>
  <li>There are two <strong>Observables</strong> (<strong>A</strong> and <strong>B</strong>) and three <strong>Observers</strong> (<strong>X</strong>, <strong>Y</strong>, and <strong>Z</strong>). </li>
  <li>Each one of those Observers and Observables are within separate (Angular) services.</li>
  <li>Observer <strong>Y</strong> observes both Observable <strong>A</strong> and Observable <strong>B</strong>, which stay "alive" over the life of the application, i.e. they do not complete.</li>
  <li>When Observable <strong>A</strong> triggers an event, Observer <strong>Y</strong> calls a function on the service of Observable <strong>B</strong>, which causes Observable <strong>B</strong> to trigger an event. Similarly, when Observable <strong>B</strong> triggers an event, Observer <strong>Y</strong> calls a function on the service of Observable <strong>A</strong>, which in turn causes Observable <strong>A</strong> to trigger an event.</li>
  </ul>
  
  <p>Ex: Observer Y...</p>
  
  <pre><code>svcA.obsA.subscribe(()=&gt; {
      svcB.doSomething()
  });
  
  svcB.obsB.subscribe(()=&gt; {
      svcA.doSomething()
  });
  </code></pre>
  
  <p>As you can see, all Observer <strong>Y</strong> is trying to do is to keep service <strong>A</strong> and service <strong>B</strong> in sync. </p>
  
  <p><strong>The problem:</strong>
  The setup as described above causes an infinite execution loop. One idea that came to my mind to get around this issue is to set a flag in each subscribe, and when that flag is set the other subscribe will ignore the next event. That is not a proper solution however because the next event may not necessarily be the one that corresponds to Observer <strong>Y</strong> calling <code>doSomething()</code>, but may be due to Observer <strong>X</strong> or <strong>Z</strong> calling <code>doSomething()</code>.</p>
  
  <p>Is there an elegant solution to this use-case? Do I have an architectural issue here? Please let me know if my description of the problem is not clear.</p>
  
  <p><strong>JSFiddles:</strong></p>
  
  <ul>
  <li><a href="https://jsfiddle.net/2g3216t5/3/" rel="nofollow noreferrer" title="JSFiddle problem example">Problem example</a></li>
  <li><a href="https://jsfiddle.net/2g3216t5/4/" rel="nofollow noreferrer" title="JSFiddle monkey patched example">Monkey patched example</a> (only ObserverY class has changed in this example)</li>
  </ul>