forked from theojulienne/go-wireless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.go
56 lines (46 loc) · 1.05 KB
/
pubsub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package wireless
import (
"strings"
)
// Subscription represents a subscription to one or events
type Subscription struct {
ch chan Event
topics string
}
func (s *Subscription) publish(ev Event) error {
if s.ch == nil {
return nil
}
// don't let slow consumers cause goroutine leak, drop
// events if the channel is full
if len(s.ch) == cap(s.ch) {
return nil
}
s.ch <- ev
return nil
}
// Next will return a channel that returns events
func (s *Subscription) Next() chan Event {
return s.ch
}
// Unsubscribe closes the channel and sets it to nil
func (s *Subscription) Unsubscribe() {
close(s.ch)
s.ch = nil
}
func (c *Conn) publishEvent(ev Event) {
for _, sub := range c.subs {
if strings.Contains(sub.topics, ev.Name) || sub.topics == "" {
sub.publish(ev)
}
}
}
// Subscribe to one or more events and return the subscription
func (c *Conn) Subscribe(eventNames ...string) *Subscription {
sub := &Subscription{
topics: strings.Join(eventNames, " "),
ch: make(chan Event, 99),
}
c.subs = append(c.subs, sub)
return sub
}