-
Notifications
You must be signed in to change notification settings - Fork 290
/
subscriber.go
66 lines (55 loc) · 1.41 KB
/
subscriber.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
package store
import (
"context"
"fmt"
"sync"
)
// A subscriber is notified whenever the state changes.
//
// Subscribers do not need to be thread-safe. The Store will only
// call OnChange for a given subscriber when the last call completes.
//
// Subscribers are only allowed to read state. If they want to
// modify state, they should call store.Dispatch()
type Subscriber interface {
OnChange(ctx context.Context, st RStore)
}
type subscriberEntry struct {
subscriber Subscriber
mu sync.Mutex
}
func (l *subscriberList) Add(s Subscriber) {
l.mu.Lock()
defer l.mu.Unlock()
l.subscribers = append(l.subscribers, &subscriberEntry{
subscriber: s,
})
}
func (l *subscriberList) Remove(s Subscriber) error {
l.mu.Lock()
defer l.mu.Unlock()
for i, current := range l.subscribers {
if s == current.subscriber {
l.subscribers = append(l.subscribers[:i], l.subscribers[i+1:]...)
return nil
}
}
return fmt.Errorf("Subscriber not found: %T: %+v", s, s)
}
func (l *subscriberList) NotifyAll(ctx context.Context, store *Store) {
l.mu.Lock()
subscribers := append([]*subscriberEntry{}, l.subscribers...)
l.mu.Unlock()
for _, s := range subscribers {
go s.notify(ctx, store)
}
}
type subscriberList struct {
subscribers []*subscriberEntry
mu sync.Mutex
}
func (e *subscriberEntry) notify(ctx context.Context, store *Store) {
e.mu.Lock()
defer e.mu.Unlock()
e.subscriber.OnChange(ctx, store)
}