From 33b3bc6a7ddca2f99683c5c3ee86b24f80a7a075 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Mon, 30 Mar 2020 14:53:01 +0300 Subject: [PATCH] Allow call Publish with nil values --- event_bus.go | 19 ++++++++++++------- event_bus_test.go | 10 +++++++--- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/event_bus.go b/event_bus.go index d4cf80f..9e66b8a 100644 --- a/event_bus.go +++ b/event_bus.go @@ -45,7 +45,7 @@ type eventHandler struct { flagOnce bool async bool transactional bool - sync.Mutex // lock for an event handler - useful for running async callbacks serially + sync.Mutex // lock for an event handler - useful for running async callbacks serially } // New returns new EventBus with empty handlers. @@ -154,7 +154,7 @@ func (bus *EventBus) Publish(topic string, args ...interface{}) { } func (bus *EventBus) doPublish(handler *eventHandler, topic string, args ...interface{}) { - passedArguments := bus.setUpPublish(topic, args...) + passedArguments := bus.setUpPublish(handler, args...) handler.callBack.Call(passedArguments) } @@ -192,12 +192,17 @@ func (bus *EventBus) findHandlerIdx(topic string, callback reflect.Value) int { return -1 } -func (bus *EventBus) setUpPublish(topic string, args ...interface{}) []reflect.Value { - - passedArguments := make([]reflect.Value, 0) - for _, arg := range args { - passedArguments = append(passedArguments, reflect.ValueOf(arg)) +func (bus *EventBus) setUpPublish(callback *eventHandler, args ...interface{}) []reflect.Value { + funcType := callback.callBack.Type() + passedArguments := make([]reflect.Value, len(args)) + for i, v := range args { + if v == nil { + passedArguments[i] = reflect.New(funcType.In(i)).Elem() + } else { + passedArguments[i] = reflect.ValueOf(v) + } } + return passedArguments } diff --git a/event_bus_test.go b/event_bus_test.go index 0cf196d..e89a0bc 100644 --- a/event_bus_test.go +++ b/event_bus_test.go @@ -73,12 +73,16 @@ func TestUnsubscribe(t *testing.T) { func TestPublish(t *testing.T) { bus := New() - bus.Subscribe("topic", func(a int, b int) { - if a != b { + bus.Subscribe("topic", func(a int, err error) { + if a != 10 { + t.Fail() + } + + if err != nil { t.Fail() } }) - bus.Publish("topic", 10, 10) + bus.Publish("topic", 10, nil) } func TestSubcribeOnceAsync(t *testing.T) {