-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy paththunk.go
58 lines (45 loc) · 881 Bytes
/
thunk.go
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
package dataloader
import (
"context"
)
type Thunk[V any] struct {
pending chan bool
data chan *thunkData[V]
}
type thunkData[V any] struct {
value V
err error
}
func NewThunk[V any]() *Thunk[V] {
thunk := &Thunk[V]{
pending: make(chan bool, 1),
data: make(chan *thunkData[V], 1),
}
thunk.pending <- true
return thunk
}
func (t *Thunk[V]) Get(ctx context.Context) (V, error) {
select {
case <-ctx.Done():
return *new(V), ctx.Err()
case v := <-t.data:
t.data <- v
return v.value, v.err
}
}
func (t *Thunk[V]) set(ctx context.Context, value V) (V, error) {
select {
case <-t.data:
case <-t.pending:
}
t.data <- &thunkData[V]{value: value}
return t.Get(ctx)
}
func (t *Thunk[V]) error(ctx context.Context, err error) (V, error) {
select {
case <-t.data:
case <-t.pending:
}
t.data <- &thunkData[V]{err: err}
return t.Get(ctx)
}