-
Notifications
You must be signed in to change notification settings - Fork 210
/
closer.go
49 lines (40 loc) · 1023 Bytes
/
closer.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
package util
import "context"
// Closer adds the ability to close objects.
type Closer struct {
channel chan struct{} // closeable go routines listen to this channel
}
// NewCloser creates a new (not closed) closer.
func NewCloser() Closer {
return Closer{make(chan struct{})}
}
// Close signals all listening instances to close.
// Note: should be called only once.
func (closer *Closer) Close() {
close(closer.channel)
}
// CloseChannel returns the channel to wait on for close signal.
func (closer *Closer) CloseChannel() chan struct{} {
return closer.channel
}
// Context returns a context which is done when channel closes.
func (closer *Closer) Context() context.Context {
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-closer.channel:
cancel()
case <-ctx.Done():
}
}()
return ctx
}
// IsClosed returns whether the channel is closed.
func (closer *Closer) IsClosed() bool {
select {
case <-closer.channel:
return true
default:
return false
}
}