Created
December 31, 2021 02:05
-
-
Save mwmitchell/57df5335634c53b33f046b8984d06337 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package api | |
import ( | |
"log" | |
"sync" | |
"time" | |
) | |
type EventBus struct { | |
mutex sync.RWMutex | |
listeners []chan HashedEntity | |
closed bool | |
} | |
func (receiver *EventBus) Send(entity HashedEntity) { | |
receiver.mutex.RLock() | |
defer receiver.mutex.RUnlock() | |
if receiver.closed { | |
return | |
} | |
for _, ch := range receiver.listeners { | |
ch <- entity | |
} | |
} | |
func (receiver *EventBus) Receive() <-chan HashedEntity { | |
receiver.mutex.Lock() | |
defer receiver.mutex.Unlock() | |
ch := make(chan HashedEntity, 1) | |
receiver.listeners = append(receiver.listeners, ch) | |
return ch | |
} | |
func (receiver *EventBus) Close() { | |
receiver.mutex.Lock() | |
defer receiver.mutex.Unlock() | |
if !receiver.closed { | |
for _, ch := range receiver.listeners { | |
close(ch) | |
} | |
receiver.closed = true | |
} | |
} | |
func NewEventBus() *EventBus { | |
eb := &EventBus{} | |
eb.listeners = make([]chan HashedEntity, 0) | |
return eb | |
} | |
func test() { | |
eb := NewEventBus() | |
ch := eb.Receive() | |
go func() { | |
time.Sleep(2 * time.Second) | |
log.Println("received ", <-ch) | |
}() | |
time.Sleep(3 * time.Second) | |
eb.Send(HashedEntity{}) | |
time.Sleep(4 * time.Second) | |
log.Printf("done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment