-
Notifications
You must be signed in to change notification settings - Fork 1
/
asyncwait.go
40 lines (35 loc) · 994 Bytes
/
asyncwait.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
package asyncwait
import "time"
// AsyncWait Represents asyncwait
type AsyncWait struct {
tickerChan <-chan time.Time
maxWaitInMillis int
doneChan chan bool
}
// NewAsyncWait Creates a new instance of AsyncWait with maxWait and pollInterval as inputs in millis
func NewAsyncWait(maxWaitInMillis int, pollIntervalInMillis int) AsyncWait {
return AsyncWait{
tickerChan: time.NewTicker(time.Millisecond * time.Duration(pollIntervalInMillis)).C,
maxWaitInMillis: maxWaitInMillis,
doneChan: make(chan bool),
}
}
// Check waits for specified maxWaitInMillis and polls every pollIntervalInMillis for the predicate truthiness
func (aw AsyncWait) Check(predicate func() bool) bool {
go func() {
time.Sleep(time.Millisecond * time.Duration(aw.maxWaitInMillis))
aw.doneChan <- false
}()
for {
select {
case <-aw.tickerChan:
go func() {
if predicate() {
aw.doneChan <- true
}
}()
case check := <-aw.doneChan:
return check
}
}
}