From d84da568bf7084581bbf96febb3d493a024c3fef Mon Sep 17 00:00:00 2001 From: Aleksey Kiselev Date: Fri, 22 Mar 2019 22:21:18 +0300 Subject: [PATCH] Fix incorrect removing handlers by index --- event_bus.go | 4 ++-- event_bus_test.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) 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() + } +}