Dispatch sends a message to all subscribed handlers of the message's type To prevent any data races, be aware that these listeners occur as callbacks and can be executed at any time. If variables are altered in the handler, utilize channels, locks, semaphores, or any other method necessary to ensure
(message Message)
| 47 | // semaphores, or any other method necessary to ensure the memory is not altered by multiple |
| 48 | // functions simultaneously. |
| 49 | func (mm *MessageManager) Dispatch(message Message) { |
| 50 | mm.RLock() |
| 51 | mm.clearRemovedHandlers() |
| 52 | handlers := make([]MessageHandler, len(mm.listeners[message.Type()])) |
| 53 | pairs := mm.listeners[message.Type()] |
| 54 | for i := range pairs { |
| 55 | handlers[i] = pairs[i].MessageHandler |
| 56 | } |
| 57 | mm.RUnlock() |
| 58 | |
| 59 | for _, handler := range handlers { |
| 60 | handler(message) |
| 61 | } |
| 62 | |
| 63 | } |
| 64 | |
| 65 | // Listen subscribes to the specified message type and calls the specified handler when fired |
| 66 | func (mm *MessageManager) Listen(messageType string, handler MessageHandler) MessageHandlerId { |