-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsumers.go
More file actions
52 lines (42 loc) · 834 Bytes
/
consumers.go
File metadata and controls
52 lines (42 loc) · 834 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
package queue
import "fmt"
type Consumer[T any] struct {
queue *Queue[T]
channel chan T
closeChannel chan struct{}
errChannel chan error
}
func NewConsumer[T any](q *Queue[T]) *Consumer[T] {
return &Consumer[T]{
queue: q,
channel: make(chan T),
closeChannel: make(chan struct{}),
errChannel: make(chan error),
}
}
func (c *Consumer[T]) Consume() <-chan T {
go func() {
for {
select {
default:
item, err := c.queue.dequeue()
if err != nil {
c.errChannel <- fmt.Errorf("queue error: %w", err)
}
c.channel <- item
case <-c.closeChannel:
return
}
}
}()
return c.channel
}
func (c *Consumer[T]) Close() error {
<-c.closeChannel
close(c.channel)
close(c.closeChannel)
return nil
}
func (c *Consumer[T]) Err() <-chan error {
return c.errChannel
}