Commit 3d2ff59 1 parent 16bb202 commit 3d2ff59 Copy full SHA for 3d2ff59
File tree 2 files changed +31
-3
lines changed
2 files changed +31
-3
lines changed Original file line number Diff line number Diff line change @@ -25,6 +25,9 @@ import (
25
25
// Runner implements the takeLatest effect from redux-saga. Its zero value
26
26
// consumes the taken message and does nothing with it.
27
27
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.
28
31
Func func (ctx context.Context , params T )
29
32
30
33
mu sync.Mutex
@@ -41,15 +44,17 @@ func (r *Runner[T]) Take(param T) {
41
44
}
42
45
r .reqs = make (chan T )
43
46
go func () {
47
+ f := func (ctx context.Context , params T ) {}
48
+ if r .Func != nil {
49
+ f = r .Func
50
+ }
44
51
cancel := func () {}
45
52
defer func () { cancel () }()
46
53
for params := range r .reqs {
47
54
cancel ()
48
55
ctx , c := context .WithCancel (context .Background ())
49
56
cancel = c
50
- if r .Func != nil {
51
- go r .Func (ctx , params )
52
- }
57
+ go f (ctx , params )
53
58
}
54
59
}()
55
60
r .reqs <- param
Original file line number Diff line number Diff line change @@ -70,3 +70,26 @@ func TestTSRBug(t *testing.T) {
70
70
t .Fatal ("trailing execution did not stop" )
71
71
}
72
72
}
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
+ }
You can’t perform that action at this time.
0 commit comments