Skip to content

Instantly share code, notes, and snippets.

@cagodoy
Created April 24, 2018 05:32
Show Gist options
  • Select an option

  • Save cagodoy/2498ef4c9297d69c3326f71a6c64f4d3 to your computer and use it in GitHub Desktop.

Select an option

Save cagodoy/2498ef4c9297d69c3326f71a6c64f4d3 to your computer and use it in GitHub Desktop.
pubsub try implementation example for golang
// Example
// pubsub := NewPubSub()
// go func() {
// for {
// pubsub.eventListener <- "PING " + string(time.Now().UnixNano())
// time.Sleep(time.Second * 3)
// }
// }()
// pubsub.AddListerner(func() {
// fmt.Println("Hola chelo")
// })
// pubsub.AddListerner(func() {
// fmt.Println("Hola camilo")
// })
// time.Sleep(time.Second * 60)
package main
import (
"fmt"
"reflect"
)
type PubSub struct {
eventListener chan string
subcribers []func()
}
// NewPubSub method
func NewPubSub() *PubSub {
return &PubSub{
eventListener: make(chan string),
}
}
// AddListerner method
// TODO: add eventName param
func (p *PubSub) AddListerner(f func()) {
p.subcribers = append(p.subcribers, f)
go func() {
for ch := range p.eventListener {
fmt.Println("EVENT LISTEN", ch)
for _, function := range p.subcribers {
function()
}
}
}()
}
// RemoveListener method
func (p *PubSub) RemoveListerner(f func()) bool {
find := false
for _, subcriber := range p.subcribers {
fValue := reflect.ValueOf(f)
sValue := reflect.ValueOf(subcriber)
if fValue.Pointer() == sValue.Pointer() {
find = true
break
}
}
return find
}
// Off method
// func (p *PubSub) Off ("*") error {
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment