Note that there are some explanatory texts on larger screens.

plurals
  1. POPublisher/Subscriber with changing subscriptions during loop
    text
    copied!<p>This is more of a general design query I had. I have implemented a publish / subscribe pattern by maintaining a list of subscribers. When an event to publish occurs, I loop through the subscribers and push the event to each one, of them in turn.</p> <p>My problem occurs when due to that publication, somewhere in the depth of the software, another component or event the described component decide to unsubscribe themselves. By doing so, they invalidate my iterator and cause crashes.</p> <p>What is the best way to solve this? I have been thinking of wrapping the whole publication loop into a try catch block, but that means some subscribers miss the particular subscription upon which someone unsubscribed, and seems a bit over the top. Then I tried feeding it back, e.g. I turned the void publish call into a bool publish call that returns true when the subscriber wants to be deleted, which works for that case, but not if another subscriber unsubscribes. Then I am thinking to "cache" unsubscription requests somewhere and release them when the loop is done, but that seems a bit overkill. Then I am thinking of storing the iterator as a class member, so that I can manipulate the iterator from outside, but that gets messy (say you unsubscribe subscriber 1, iterator is pointed at 2, and the container is a vector - then the iterator would have to be decremented). I think I might prefer one of the latter two solutions, but both seem not ideal.</p> <p>Is this a common problem? Is there a more elegant solution?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload