...
1 package diodes
2
3 import (
4 "context"
5 "time"
6 )
7
8
9 type Diode interface {
10 Set(GenericDataType)
11 TryNext() (GenericDataType, bool)
12 }
13
14
15 type Poller struct {
16 Diode
17 interval time.Duration
18 ctx context.Context
19 }
20
21
22 type PollerConfigOption func(*Poller)
23
24
25
26 func WithPollingInterval(interval time.Duration) PollerConfigOption {
27 return func(c *Poller) {
28 c.interval = interval
29 }
30 }
31
32
33
34
35 func WithPollingContext(ctx context.Context) PollerConfigOption {
36 return func(c *Poller) {
37 c.ctx = ctx
38 }
39 }
40
41
42 func NewPoller(d Diode, opts ...PollerConfigOption) *Poller {
43 p := &Poller{
44 Diode: d,
45 interval: 10 * time.Millisecond,
46 ctx: context.Background(),
47 }
48
49 for _, o := range opts {
50 o(p)
51 }
52
53 return p
54 }
55
56
57
58 func (p *Poller) Next() GenericDataType {
59 for {
60 data, ok := p.Diode.TryNext()
61 if !ok {
62 if p.isDone() {
63 return nil
64 }
65
66 time.Sleep(p.interval)
67 continue
68 }
69 return data
70 }
71 }
72
73 func (p *Poller) isDone() bool {
74 select {
75 case <-p.ctx.Done():
76 return true
77 default:
78 return false
79 }
80 }
81
View as plain text