Created
April 24, 2018 05:32
-
-
Save cagodoy/2498ef4c9297d69c3326f71a6c64f4d3 to your computer and use it in GitHub Desktop.
pubsub try implementation example for golang
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
| // 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