allow for/range with Feed

This commit is contained in:
2024-08-22 16:04:37 +01:00
parent 016d248ebd
commit e05061d31d

View File

@@ -3,6 +3,7 @@ package gubgub
import (
"context"
"fmt"
"iter"
"sync"
)
@@ -128,6 +129,32 @@ func (t *AsyncTopic[T]) Subscribe(fn Subscriber[T]) error {
return nil
}
// Feed allows the usage of for/range to consume future published messages. The supporting subscriber will eventually be discarded after you exit the for loop.
func (t *AsyncTopic[T]) Feed() iter.Seq[T] {
feed := make(chan T, 1)
done := make(chan struct{})
t.Subscribe(func(msg T) bool {
select {
case feed <- msg:
return true
case <-done:
close(feed)
return false
}
})
return func(yield func(T) bool) {
defer close(done)
for msg := range feed {
if !yield(msg) {
return
}
}
}
}
type AsyncTopicOptions struct {
onClose func()
onSubscribe func(count int)