github.com/ethersphere/bee/v2@v2.2.0/pkg/storer/internal/events/subscribe.go (about) 1 // Copyright 2023 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package events 6 7 import ( 8 "sync" 9 ) 10 11 type Subscriber struct { 12 mtx sync.Mutex 13 subs map[string][]chan struct{} 14 } 15 16 func NewSubscriber() *Subscriber { 17 return &Subscriber{ 18 subs: make(map[string][]chan struct{}), 19 } 20 } 21 22 func (b *Subscriber) Subscribe(str string) (<-chan struct{}, func()) { 23 b.mtx.Lock() 24 defer b.mtx.Unlock() 25 26 c := make(chan struct{}, 1) 27 b.subs[str] = append(b.subs[str], c) 28 29 return c, func() { 30 b.mtx.Lock() 31 defer b.mtx.Unlock() 32 33 for i, s := range b.subs[str] { 34 if s == c { 35 b.subs[str][i] = nil 36 b.subs[str] = append(b.subs[str][:i], b.subs[str][i+1:]...) 37 break 38 } 39 } 40 } 41 } 42 43 func (b *Subscriber) Trigger(str string) { 44 b.mtx.Lock() 45 defer b.mtx.Unlock() 46 47 for _, s := range b.subs[str] { 48 select { 49 case s <- struct{}{}: 50 default: 51 } 52 } 53 }