Skip to content

Commit

Permalink
fix: add once close
Browse files Browse the repository at this point in the history
Signed-off-by: gfanton <[email protected]>
  • Loading branch information
gfanton committed Nov 15, 2023
1 parent 973414a commit a96cdc6
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions tm2/pkg/events/subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package events
import (
"log"
"reflect"
"sync"
"time"
)

Expand Down Expand Up @@ -40,10 +41,12 @@ func SubscribeFiltered(evsw EventSwitch, listenerID string, filter EventFilter)
}

func SubscribeFilteredOn(evsw EventSwitch, listenerID string, filter EventFilter, ch chan Event) <-chan Event {
var onceClose sync.Once
evsw.AddListener(listenerID, func(event Event) {
if filter != nil && !filter(event) {
return // filter
}

// NOTE: This callback must not block for performance.
if cap(ch) == 0 {
timeout := 10 * time.Second
Expand All @@ -53,7 +56,7 @@ func SubscribeFilteredOn(evsw EventSwitch, listenerID string, filter EventFilter
case ch <- event:
break LOOP
case <-evsw.Quit():
close(ch)
onceClose.Do(func() { close(ch) })
break LOOP
case <-time.After(timeout):
// After a minute, print a message for debugging.
Expand All @@ -67,7 +70,7 @@ func SubscribeFilteredOn(evsw EventSwitch, listenerID string, filter EventFilter
case ch <- event:
default: // async
evsw.RemoveListener(listenerID) // TODO log
close(ch)
onceClose.Do(func() { close(ch) })
}
}
})
Expand Down

0 comments on commit a96cdc6

Please sign in to comment.