Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support unsubscribe in connect mode #334

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 39 additions & 6 deletions iterable_channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@ import (
"sync"
)

type subscription struct {
ctx context.Context
ch chan Item
}

type channelIterable struct {
next <-chan Item
opts []Option
subscribers []chan Item
nextSubscriberID uint64
subscribers map[uint64]*subscription
mutex sync.RWMutex
producerAlreadyCreated bool
}

func newChannelIterable(next <-chan Item, opts ...Option) Iterable {
return &channelIterable{
next: next,
subscribers: make([]chan Item, 0),
subscribers: make(map[uint64]*subscription),
opts: opts,
}
}
Expand All @@ -34,9 +40,21 @@ func (i *channelIterable) Observe(opts ...Option) <-chan Item {
return nil
}

ch := i.createSubscription(option)
return ch
}

func (i *channelIterable) createSubscription(option Option) chan Item {
ch := option.buildChannel()
sctx := option.buildContext(emptyContext)

i.mutex.Lock()
i.subscribers = append(i.subscribers, ch)
sid := i.nextSubscriberID
i.nextSubscriberID++
i.subscribers[sid] = &subscription{
ctx: sctx,
ch: ch,
}
i.mutex.Unlock()
return ch
}
Expand All @@ -54,7 +72,7 @@ func (i *channelIterable) produce(ctx context.Context) {
defer func() {
i.mutex.RLock()
for _, subscriber := range i.subscribers {
close(subscriber)
close(subscriber.ch)
}
i.mutex.RUnlock()
}()
Expand All @@ -67,11 +85,26 @@ func (i *channelIterable) produce(ctx context.Context) {
if !ok {
return
}
toBeCleaned := make([]uint64, 0)
i.mutex.RLock()
for _, subscriber := range i.subscribers {
subscriber <- item
for sid, subscriber := range i.subscribers {
select {
case <-subscriber.ctx.Done():
toBeCleaned = append(toBeCleaned, sid)
case subscriber.ch <- item:
}
}
i.mutex.RUnlock()

i.removeSubscriptions(toBeCleaned)
}
}
}

func (i *channelIterable) removeSubscriptions(sids []uint64) {
i.mutex.Lock()
defer i.mutex.Unlock()
for _, sid := range sids {
delete(i.subscribers, sid)
}
}