Skip to content

Commit

Permalink
Merge pull request #4 from vitalyisaev2/master
Browse files Browse the repository at this point in the history
CFS-2079 | feat: fire predicate one time immediately, start polling after
  • Loading branch information
lebovski authored Sep 6, 2021
2 parents c5857e5 + b3a13d6 commit 8d6a9b5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
20 changes: 18 additions & 2 deletions asyncwait.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,34 @@ 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 8d6a9b5

Please sign in to comment.