-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwork.go
More file actions
59 lines (51 loc) · 849 Bytes
/
work.go
File metadata and controls
59 lines (51 loc) · 849 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package workchain
import "context"
type Work struct {
prev *Work
next *Work
do DoFunc
cond CondFunc
}
type DoFunc func(ctx context.Context) error
func NewWork(do func(ctx context.Context) error) *Work {
return &Work{
do: do,
}
}
func (w *Work) WithCond(cond CondFunc) *Work {
cw := *w
cw.cond = cond
return &cw
}
func (w *Work) Do(ctx context.Context) error {
cw := w
for {
if cw == nil {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
default:
ok, ctx, err := cw.ok(ctx)
if err != nil {
return err
}
if !ok {
return nil
}
if cw.do != nil {
if err := cw.do(ctx); err != nil {
return err
}
}
cw = cw.next
}
}
}
func (w *Work) ok(ctx context.Context) (bool, context.Context, error) {
if w.cond == nil {
return true, ctx, nil
}
return w.cond(ctx)
}