Debian Codegraph @

hub.go

raw symbols SCIP
1 // Package hub provides a simple event dispatcher for publish/subscribe pattern.
2 package hub
3
4 import "sync"
5
6 type Kind int
7
8 // Event is an interface for published events.
9 type Event interface {
10 Kind() Kind
11 }
12
13 // Hub is an event dispatcher, publishes events to the subscribers
14 // which are subscribed for a specific event type.
15 // Optimized for publish calls.
16 // The handlers may be called in order different than they are registered.
17 type Hub struct {
18 subscribers map[Kind][]handler
19 m sync.RWMutex
20 seq uint64
21 }
22
23 type handler struct {
24 f func(Event)
25 id uint64
26 }
27
28 // Subscribe registers f for the event of a specific kind.
29 func (h *Hub) Subscribe(kind Kind, f func(Event)) (cancel func()) {
30 var cancelled bool
31 h.m.Lock()
32 h.seq++
33 id := h.seq
34 if h.subscribers == nil {
35 h.subscribers = make(map[Kind][]handler)
36 }
37 h.subscribers[kind] = append(h.subscribers[kind], handler{id: id, f: f})
38 h.m.Unlock()
39 return func() {
40 h.m.Lock()
41 if cancelled {
42 h.m.Unlock()
43 return
44 }
45 cancelled = true
46 a := h.subscribers[kind]
47 for i, f := range a {
48 if f.id == id {
49 a[i], h.subscribers[kind] = a[len(a)-1], a[:len(a)-1]
50 break
51 }
52 }
53 if len(a) == 0 {
54 delete(h.subscribers, kind)
55 }
56 h.m.Unlock()
57 }
58 }
59
60 // Publish an event to the subscribers.
61 func (h *Hub) Publish(e Event) {
62 h.m.RLock()
63 if handlers, ok := h.subscribers[e.Kind()]; ok {
64 for _, h := range handlers {
65 h.f(e)
66 }
67 }
68 h.m.RUnlock()
69 }
70
71 // DefaultHub is the default Hub used by Publish and Subscribe.
72 var DefaultHub Hub
73
74 // Subscribe registers f for the event of a specific kind in the DefaultHub.
75 func Subscribe(kind Kind, f func(Event)) (cancel func()) {
76 return DefaultHub.Subscribe(kind, f)
77 }
78
79 // Publish an event to the subscribers in DefaultHub.
80 func Publish(e Event) {
81 DefaultHub.Publish(e)
82 }