forked from cloudfoundry/go-diodes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
waiter.go
71 lines (61 loc) · 1.52 KB
/
waiter.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
package diodes
import (
"context"
)
// Waiter will use a channel signal to alert the reader to when data is
// available.
type Waiter struct {
Diode
c chan struct{}
ctx context.Context
}
// WaiterConfigOption can be used to setup the waiter.
type WaiterConfigOption func(*Waiter)
// WithWaiterContext sets the context to cancel any retrieval (Next()). It
// will not change any results for adding data (Set()). Default is
// context.Background().
func WithWaiterContext(ctx context.Context) WaiterConfigOption {
return WaiterConfigOption(func(c *Waiter) {
c.ctx = ctx
})
}
// NewWaiter returns a new Waiter that wraps the given diode.
func NewWaiter(d Diode, opts ...WaiterConfigOption) *Waiter {
w := new(Waiter)
w.Diode = d
w.c = make(chan struct{}, 1)
w.ctx = context.Background()
for _, opt := range opts {
opt(w)
}
return w
}
// Set invokes the wrapped diode's Set with the given data and uses broadcast
// to wake up any readers.
func (w *Waiter) Set(data GenericDataType) {
w.Diode.Set(data)
w.broadcast()
}
// broadcast sends to the channel if it can.
func (w *Waiter) broadcast() {
select {
case w.c <- struct{}{}:
default:
}
}
// Next returns the next data point on the wrapped diode. If there is no new
// data, it will wait for Set to be called or the context to be done. If the
// context is done, then nil will be returned.
func (w *Waiter) Next() GenericDataType {
for {
data, ok := w.Diode.TryNext()
if ok {
return data
}
select {
case <-w.ctx.Done():
return nil
case <-w.c:
}
}
}