Skip to content

Commit

Permalink
CFS-2079 | feat: fire predicate one time immediately, start polling a…
Browse files Browse the repository at this point in the history
…fter
  • Loading branch information
Vitaly Isaev committed Sep 6, 2021
1 parent c5857e5 commit 4132891
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
21 changes: 18 additions & 3 deletions asyncwait.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,33 @@ func NewAsyncWait(timeout, pollInterval time.Duration) AsyncWait {
}
}

// Wait while timeout, make polls every pollInterval for the predicate while is not truth
// Wait while timeout, make polls every pollInterval for the predicate until it returns true
func (aw asyncWait) Wait(predicate func() bool) bool {
ctx, cancel := context.WithTimeout(context.Background(), aw.timeout)
defer cancel()

ticker := time.NewTicker(aw.pollInterval)
defer ticker.Stop()

runPredicate := func() {
if predicate() {
select {
case aw.doneCh <- struct{}{}:
case <-ctx.Done():
}
}
}

// Try to execute predicate immediately
go runPredicate()

// If the first call was not successful, start polling
for {
select {
case <-aw.doneCh:
return true
case <-ctx.Done():
return false
case <-time.After(aw.pollInterval):
case <-ticker.C:
go func() {
if predicate() {
select {
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/vitalyisaev2/asyncwait

go 1.16

0 comments on commit 4132891

Please sign in to comment.