From 22e0eb3f23a4aef11916f2b4bcea67cd90aa8e17 Mon Sep 17 00:00:00 2001 From: Thomas Weber Date: Thu, 12 Nov 2020 21:28:06 +0100 Subject: [PATCH] Fixed SubscribeOnce unsubscribe handling --- event_bus.go | 6 ++++-- event_bus_test.go | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) 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() } }