diff --git a/event_bus.go b/event_bus.go index dedc7fd..718cd4f 100644 --- a/event_bus.go +++ b/event_bus.go @@ -136,9 +136,11 @@ func (bus *EventBus) Publish(topic string, args ...interface{}) { // so make a copy and iterate the copied slice. copyHandlers := make([]*eventHandler, len(handlers)) copy(copyHandlers, handlers) - for i, handler := range copyHandlers { + for _, handler := range copyHandlers { if handler.flagOnce { - bus.removeHandler(topic, i) + // do not rely on copied index, instead lookup the handler in the + // possibly altered original list + bus.removeHandler(topic, bus.findHandlerIdx(topic, handler.callBack)) } if !handler.async { bus.doPublish(handler, topic, args...) diff --git a/event_bus_test.go b/event_bus_test.go index 0cdb579..7c37a3b 100644 --- a/event_bus_test.go +++ b/event_bus_test.go @@ -52,9 +52,14 @@ func TestSubscribeOnceAndManySubscribe(t *testing.T) { bus.SubscribeOnce(event, fn) bus.Subscribe(event, fn) bus.Subscribe(event, fn) + bus.SubscribeOnce(event, fn) bus.Publish(event) - if flag != 3 { + if flag != 4 { + t.Fail() + } + bus.Publish(event) + if flag != 6 { t.Fail() } }