-
Notifications
You must be signed in to change notification settings - Fork 5
/
subscriptions.go
77 lines (61 loc) · 1.47 KB
/
subscriptions.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package execution
import "sync"
type Subscription[T interface{}] struct {
//nolint:structcheck // linter bug with generic struct
channel chan T
//nolint:structcheck // linter bug with generic struct
dispatcher *Dispatcher[T]
}
type Dispatcher[T interface{}] struct {
//nolint:structcheck // linter bug with generic struct
mutex sync.Mutex
//nolint:structcheck // linter bug with generic struct
subscriptions []*Subscription[T]
}
func (d *Dispatcher[T]) Subscribe(capacity int) *Subscription[T] {
d.mutex.Lock()
defer d.mutex.Unlock()
subscription := &Subscription[T]{
channel: make(chan T, capacity),
dispatcher: d,
}
d.subscriptions = append(d.subscriptions, subscription)
return subscription
}
func (s *Subscription[T]) Unsubscribe() {
if s.dispatcher == nil {
return
}
s.dispatcher.Unsubscribe(s)
}
func (s *Subscription[T]) Channel() <-chan T {
return s.channel
}
func (d *Dispatcher[T]) Unsubscribe(subscription *Subscription[T]) {
d.mutex.Lock()
defer d.mutex.Unlock()
if subscription.dispatcher != nil {
return
}
count := len(d.subscriptions)
for i, s := range d.subscriptions {
if s == subscription {
if i < count-1 {
d.subscriptions[i] = d.subscriptions[count-1]
}
d.subscriptions = d.subscriptions[:count-1]
subscription.dispatcher = nil
return
}
}
}
func (d *Dispatcher[T]) Fire(data T) {
d.mutex.Lock()
defer d.mutex.Unlock()
for _, s := range d.subscriptions {
select {
case s.channel <- data:
default:
}
}
}