Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unsubscribe and closures #47

Open
paleozogt opened this issue Nov 10, 2020 · 2 comments
Open

unsubscribe and closures #47

paleozogt opened this issue Nov 10, 2020 · 2 comments

Comments

@paleozogt
Copy link

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.

@paleozogt
Copy link
Author

Some ideas for fixing it:

  • Have clients pass in an explicit id to Subscribe/Unsubscribe along with the func

    bus.Subscribe("foo", "handler2", handler2)
    bus.Unsubscribe("foo", "handler2")
    
  • Subscribe could return a handle that could be used for Unsubscribe

    h1 := bus.Subscribe("foo", handler2)
    bus.Unsubscribe(h1)
    
  • Have clients pass in a struct that wraps the function, guaranteeing a unique pointer

    h1 := Handler{ Func: handler1 }
    bus.Subscribe("foo", &h1)
    bus.Unsubscribe("foo", &h1)
    

@LubosD
Copy link

LubosD commented Sep 8, 2022

I've just hit this bug. As I show in this playground, you can just use plain == to compare reflect.Values containing lambdas and it seems to work correcly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants