-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubscription.go
61 lines (53 loc) · 1.13 KB
/
subscription.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
package rxgo
import (
"reflect"
"sync"
)
type Subscription interface {
Unsubscribe()
Add(TeardownFunc) Subscription
Remove(Subscription)
Wait()
}
type subscription struct {
mtx sync.Mutex
TeardownFunc
done chan bool
subscriptions []Subscription
}
func NewSubscription(teardown TeardownFunc) *subscription {
return &subscription{TeardownFunc: teardown, done: make(chan bool, 1)}
}
func (s *subscription) Unsubscribe() {
s.mtx.Lock()
defer s.mtx.Unlock()
select {
case s.done <- true:
for _, sub := range s.subscriptions {
sub.Unsubscribe()
}
if s.TeardownFunc != nil {
s.TeardownFunc()
}
default:
}
}
func (s *subscription) Add(teardown TeardownFunc) Subscription {
s.mtx.Lock()
defer s.mtx.Unlock()
sub := NewSubscription(teardown)
s.subscriptions = append(s.subscriptions, sub)
return sub
}
func (s *subscription) Remove(subscription Subscription) {
s.mtx.Lock()
defer s.mtx.Unlock()
for i := range s.subscriptions {
if reflect.DeepEqual(s.subscriptions[i], subscription) {
s.subscriptions = append(s.subscriptions[:i], s.subscriptions[i+1:]...)
}
}
}
func (s *subscription) Wait() {
<-s.done
}