Skip to content

Commit 3d2ff59

Browse files
committed
ensure Func cannot be changed one the runner starts
1 parent 16bb202 commit 3d2ff59

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

takelatest.go

+8-3
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ import (
2525
// Runner implements the takeLatest effect from redux-saga. Its zero value
2626
// consumes the taken message and does nothing with it.
2727
type Runner[T any] struct {
28+
// Func executes the desired work. Observe context cancellation to know
29+
// when the next (aka latest) call comes in. Func cannot be replaced
30+
// when the Runner is active, you must Close first.
2831
Func func(ctx context.Context, params T)
2932

3033
mu sync.Mutex
@@ -41,15 +44,17 @@ func (r *Runner[T]) Take(param T) {
4144
}
4245
r.reqs = make(chan T)
4346
go func() {
47+
f := func(ctx context.Context, params T) {}
48+
if r.Func != nil {
49+
f = r.Func
50+
}
4451
cancel := func() {}
4552
defer func() { cancel() }()
4653
for params := range r.reqs {
4754
cancel()
4855
ctx, c := context.WithCancel(context.Background())
4956
cancel = c
50-
if r.Func != nil {
51-
go r.Func(ctx, params)
52-
}
57+
go f(ctx, params)
5358
}
5459
}()
5560
r.reqs <- param

takelatest_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,26 @@ func TestTSRBug(t *testing.T) {
7070
t.Fatal("trailing execution did not stop")
7171
}
7272
}
73+
74+
func TestChangingFunc(t *testing.T) {
75+
// The runner must not allow Func to be updated on the fly
76+
observed := make(chan struct{})
77+
r := Runner[any]{}
78+
r.Take(nil)
79+
r.Func = func(context.Context, any) {
80+
observed <- struct{}{}
81+
}
82+
r.Take(nil)
83+
select {
84+
case <-observed:
85+
t.Fatal("runner must not be reconfigurable once started")
86+
case <-time.After(1 * time.Second):
87+
}
88+
r.Close()
89+
r.Take(nil)
90+
select {
91+
case <-observed:
92+
case <-time.After(1 * time.Second):
93+
t.Fatal("runner must be reconfigurable once closed")
94+
}
95+
}

0 commit comments

Comments
 (0)