Allow call Publish with nil values

This commit is contained in:
ErickSkrauch
2020-03-30 14:53:01 +03:00
parent d46933a94f
commit 33b3bc6a7d
2 changed files with 19 additions and 10 deletions

View File

@@ -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
}

View File

@@ -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) {