-
Notifications
You must be signed in to change notification settings - Fork 338
/
subscribe.go
53 lines (43 loc) · 947 Bytes
/
subscribe.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
// Copyright 2023 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"sync"
)
type Subscriber struct {
mtx sync.Mutex
subs map[string][]chan struct{}
}
func NewSubscriber() *Subscriber {
return &Subscriber{
subs: make(map[string][]chan struct{}),
}
}
func (b *Subscriber) Subscribe(str string) (<-chan struct{}, func()) {
b.mtx.Lock()
defer b.mtx.Unlock()
c := make(chan struct{}, 1)
b.subs[str] = append(b.subs[str], c)
return c, func() {
b.mtx.Lock()
defer b.mtx.Unlock()
for i, s := range b.subs[str] {
if s == c {
b.subs[str][i] = nil
b.subs[str] = append(b.subs[str][:i], b.subs[str][i+1:]...)
break
}
}
}
}
func (b *Subscriber) Trigger(str string) {
b.mtx.Lock()
defer b.mtx.Unlock()
for _, s := range b.subs[str] {
select {
case s <- struct{}{}:
default:
}
}
}