Created
May 7, 2013 21:35
-
-
Save gregghz/5536341 to your computer and use it in GitHub Desktop.
An example of a primitive way to implement an event system in Go using channels and goroutines.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type SomeEvent struct { | |
callbacks []func(int) | |
cc chan int | |
} | |
func NewSomeEvent() *SomeEvent { | |
se := &SomeEvent{ | |
[]func(int){}, | |
make(chan int), | |
} | |
// start up the goroutine that watches for events | |
go func() { | |
// reads from the channel until it's closed (blocks while the channel is empty) | |
for i := range se.cc { | |
// loop over all the callback passing the most recently read value from the channel | |
for _, call := range se.callbacks { | |
call(i) | |
} | |
} | |
}() | |
return se | |
} | |
func (s *SomeEvent) register(f func(int)) { | |
s.callbacks = append(s.callbacks, f) | |
} | |
func (s *SomeEvent) fire(i int) { | |
s.cc <- i | |
} | |
// create the event thingy as global for convenience. | |
// There are probably better ways to handle this. | |
var someEvent = NewSomeEvent() | |
func main() { | |
// register a couple handlers | |
someEvent.register(func (i int) { | |
fmt.Println("Some Event (1): ", i) | |
}) | |
someEvent.register(func (i int) { | |
fmt.Println("Some Event (2): ", i) | |
}) | |
// fire the events | |
someEvent.fire(12) | |
someEvent.fire(1) | |
someEvent.fire(-42) | |
} | |
// $ go run events.go | |
// Some Event (1): 12 | |
// Some Event (2): 12 | |
// Some Event (1): 1 | |
// Some Event (2): 1 | |
// Some Event (1): -42 | |
// Some Event (2): -42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment