Consider the following scenario:
observerX => observableA <= observerY => observableB <= observerZ
- There are two Observables (A and B) and three Observers (X, Y, and Z).
- Each one of those Observers and Observables are within separate (Angular) services.
- Observer Y observes both Observable A and Observable B, which stay "alive" over the life of the application, i.e. they do not complete.
- When Observable A triggers an event, Observer Y calls a function on the service of Observable B, which causes Observable B to trigger an event. Similarly, when Observable B triggers an event, Observer Y calls a function on the service of Observable A, which in turn causes Observable A to trigger an event.
Ex: Observer Y...
svcA.obsA.subscribe(()=> {
svcB.doSomething()
});
svcB.obsB.subscribe(()=> {
svcA.doSomething()
});
As you can see, all Observer Y is trying to do is to keep service A and service B in sync.
The problem:
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 Y calling doSomething(), but may be due to Observer X or Z calling doSomething().
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.
JSFiddles:
- Problem example
- Monkey patched example (only ObserverY class has changed in this example)
