diff --git a/event_bus.go b/event_bus.go index d4cf80f..23b1d34 100644 --- a/event_bus.go +++ b/event_bus.go @@ -136,9 +136,9 @@ func (bus *EventBus) Publish(topic string, args ...interface{}) { // so make a copy and iterate the copied slice. copyHandlers := make([]*eventHandler, 0, len(handlers)) copyHandlers = append(copyHandlers, handlers...) - for i, handler := range copyHandlers { + for _, handler := range copyHandlers { if handler.flagOnce { - bus.removeHandler(topic, i) + 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 0cf196d..2caa599 100644 --- a/event_bus_test.go +++ b/event_bus_test.go @@ -154,3 +154,20 @@ func TestSubscribeAsync(t *testing.T) { t.Fail() } } + +func TestManySubscribeOnce(t *testing.T) { + bus := New() + event := "topic" + var flags [3]byte + + bus.SubscribeOnce(event, func() { flags[0]++ }) + bus.SubscribeOnce(event, func() { flags[1]++ }) + bus.Subscribe(event, func() { flags[2]++ }) + + bus.Publish(event) + bus.Publish(event) + + if flags != [3]byte{1, 1, 2} { + t.Fail() + } +}