Over 10 years of community discussion and knowledge are maintained here as a read-only archive.
1) Go backwards through the notification list instead of forwards so that removals from the list don't matter. 2) Keep track of the observers traversed so far in a separate array. After each notification pass through the traversed list and see if any are now missing from the observer list and if so drop them from the traversed list and decrement the traversed list pointer and keep going, counting the total we discover to have been removed. Then decrement the outer notification loop by the total removed and continue notification.3) Copy all the observers to a new array and notify by iterating over the copy. So removals from the actual observer list don't affect the list we're iterating over at all.
#1 - Doesn't add any logic or extra cycles, but might cause undesired side effects and is somewhat counter-intuitive to how you would expect notification to work. It's short, but not so sweet if you were depending on notification following the order of observer registration.#2 - Is a valiant effort which really appears to hold water, but monkeying with nested iterators is not pretty to debug, and it would eat up an awful lot of extra cycles for this relative boundary case on every notification.#3 - Is an elegant approach that really cuts to the heart of the problem - the iterated array may change mid-traverse, so don't work with a reference at all. It'll add the overhead of an extra loop to copy the list each time, but it we're shielded from changes to the original list and don't have to add any logic to the notification loop.
Ok folks.Looking at these topics merged, we have 3 proposed solutions that should work:#3 looks like the right approach to me.-=Cliff>
What about a situation where a Mediator is removing Mediators further down in the observers array? The Mediator will get removed from the original observers array, but will continue to exist in its copy, which will obviously be disastrous once the second loop reaches those Mediators that are no longer supposed to exist.