Skip to content

unsubscribe and closures #47

@paleozogt

Description

@paleozogt

Unsubscribe is broken with closures. This code shows the problem:

makeHandler := func(tag string) func(msg string) {
	return func(msg string) {
		fmt.Printf("%s %s\n", tag, msg)
	}
}

var bus EventBus.Bus = EventBus.New()

handler1 := makeHandler("handler1")
fmt.Printf("handler1 pointer %x\n", reflect.ValueOf(handler1).Pointer())
bus.Subscribe("foo", handler1)

handler2 := makeHandler("handler2")
fmt.Printf("handler2 pointer %x\n", reflect.ValueOf(handler2).Pointer())
bus.Subscribe("foo", handler2)

bus.Publish("foo", "A")
bus.Unsubscribe("foo", handler2)
bus.Publish("foo", "B")

Here's the output:

handler1 pointer 11ac100
handler2 pointer 11ac100
handler1 A
handler2 A
handler2 B

Note that even though we removed handler2, it still got an the B event.

What's happening is that EventBus uses reflect.ValueOf().Pointer() for Unsubscribe. However, the pointer to a function isn't enough to distinguish one closure from another. You can see the problem in the above output where it shows that the pointer values for handler1 and handler2 are the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions