-
Notifications
You must be signed in to change notification settings - Fork 1
/
async.go
77 lines (70 loc) · 1.62 KB
/
async.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package goneric
import "sync"
// Async runs a function in goroutine and returns pipe with result
func Async[T1 any](f func() T1) chan T1 {
out := make(chan T1, 1)
go func() {
out <- f()
}()
return out
}
// AsyncV runs a number of functions in goroutine and returns pipe with result then closes after goroutines finish
// order is not guaranteed
func AsyncV[T1 any](funcList ...func() T1) chan T1 {
out := make(chan T1, 1)
wg := sync.WaitGroup{}
for _, f := range funcList {
wg.Add(1)
go func(f func() T1) {
out <- f()
wg.Done()
}(f)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
// AsyncVUnpanic runs a number of functions in goroutine and returns pipe with result then closes after goroutines finish
// order is not guaranteed
// panics are suppressed
func AsyncVUnpanic[T1 any](funcList ...func() T1) chan T1 {
out := make(chan T1, 1)
wg := sync.WaitGroup{}
for _, f := range funcList {
wg.Add(1)
go func(f func() T1) {
defer func() {
wg.Done()
recover()
}()
out <- f()
}(f)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
// AsyncPipe runs a function in goroutine from input channel and returns pipe with result
func AsyncPipe[T1, T2 any](in chan T1, f func(T1) T2) chan T2 {
out := make(chan T2, 1)
go func() {
out <- f(<-in)
}()
return out
}
// AsyncOut takes value and feeds it to function returning asynchronously to channel
func AsyncOut[T1, T2 any](in chan T1, f func(T1) T2, out chan T2) {
go func() {
out <- f(<-in)
}()
}
// AsyncIn turns value into channel with value
func AsyncIn[T1 any](in T1) (out chan T1) {
out = make(chan T1, 1)
out <- in
return out
}