Skip to content

Commit

Permalink
add defered param to AsyncRepeat
Browse files Browse the repository at this point in the history
  • Loading branch information
streamz committed Apr 27, 2020
1 parent 90ab86a commit f2c33dd
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 11 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Unfortunately higher order functions require the use of reflection, so they are
```golang
Apply(fn F, args ...T) (func()T, error)

AsyncRepeat(fn F) func()
AsyncRepeat(fn F, defered func()) func()

Compare(t0 T, t1 T, fn F) (bool, error)

Expand Down Expand Up @@ -52,7 +52,9 @@ Reduce(initial T, t T, fn F) (T, error)
// AsyncRepeat
stop := AsyncRepeat(F{func() {
// do something
}})
}}, func() {
// do something defered
})

// stop doing something
stop()
Expand Down
14 changes: 10 additions & 4 deletions hof.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,19 @@ func Apply(fn F, args ...T) (func()T, error) {
// AsyncRepeat executes a Nullary F in a goroutine until result is executed"
// cancel := AsyncRepeat(F{func() {
// // do something
// }})
// }}, func() {
// // defered do something
// })
// // Stop doing something
// cancel()
func AsyncRepeat(fn F) func() {
func AsyncRepeat(fn F, defered func()) func() {
c := make(chan _U)

cancel := func() {
close(c)
}
go fn.until(c)

go fn.until(c, defered)

return cancel
}
Expand Down Expand Up @@ -254,7 +258,9 @@ func (fn F) apply(args ...T) (func()T, error) {
return res, nil
}

func (fn F) until(c chan _U) {
func (fn F) until(c chan _U, defered func()) {
defer defered()

fn.assert(_R{_K{},_K{}})
f := reflect.ValueOf(fn.I)
running := func(ch chan _U) bool {
Expand Down
27 changes: 22 additions & 5 deletions hof_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ package ginsu

import (
"errors"
"sync"
"testing"
"time"
)

type point struct {
Expand All @@ -32,16 +32,33 @@ type line struct {
func TestAsyncRepeat(t *testing.T) {
e := errors.New("TestAsyncRepeat Failed")
count := 0
invoked := false

var wg0 sync.WaitGroup
wg0.Add(1)

defered := func() {
defer wg0.Done()
invoked = true
}

var wg1 sync.WaitGroup
wg1.Add(5)

stop := AsyncRepeat(F{func() {
if count < 5 {
count++
}
}})
wg1.Done()
}
}}, defered)

wg1.Wait()

time.Sleep(1000 * time.Millisecond)
stop()

if count != 5 {
wg0.Wait()

if count != 5 || !invoked {
t.Errorf(e.Error())
}
}
Expand Down

0 comments on commit f2c33dd

Please sign in to comment.