-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathordone.go
More file actions
36 lines (32 loc) · 795 Bytes
/
Copy pathordone.go
File metadata and controls
36 lines (32 loc) · 795 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
package syncx
import "context"
// OrDone forwards values from in until in closes or ctx is cancelled,
// making a plain `for v := range ch` loop cancellable without nested
// selects at the call site.
//
// The returned channel is unbuffered and is always closed when the
// forwarding goroutine exits, so consumers never block forever and the
// goroutine never leaks. Values already sent by the producer but not yet
// forwarded when ctx is cancelled are dropped.
func OrDone[T any](ctx context.Context, in <-chan T) <-chan T {
out := make(chan T)
go func() {
defer close(out)
for {
select {
case <-ctx.Done():
return
case v, ok := <-in:
if !ok {
return
}
select {
case out <- v:
case <-ctx.Done():
return
}
}
}
}()
return out
}