@@ -13,6 +13,11 @@ type iEventName interface {
1313 EventID () string //
1414}
1515
16+ // if developers implement this interface, we're spinning a goroutine if the event says it is async
17+ type iAsync interface {
18+ Async () bool
19+ }
20+
1621// Listener is being returned when you subscribe to a topic, so you can unsubscribe or access the parent topic
1722type Listener [T any ] struct {
1823 parent * Topic [T ] // so we can call unsubscribe from parent
@@ -90,17 +95,32 @@ func (s *Listener[T]) Topic() *Topic[T] {
9095// Pub allows you to publish an event in that topic
9196func (b * Topic [T ]) Pub (event T ) {
9297 b .rwMu .RLock ()
93- for topic := range b .subs {
94- b .subs [topic ].callback (event )
98+
99+ isAsync := false
100+ switch m := any (event ).(type ) {
101+ case iAsync :
102+ isAsync = m .Async ()
95103 }
104+
105+ for sub := range b .subs {
106+ if isAsync {
107+ go b .subs [sub ].callback (event )
108+ continue
109+ }
110+
111+ b .subs [sub ].callback (event )
112+ }
113+
96114 b .rwMu .RUnlock ()
97115}
98116
99117func (b * Topic [T ]) PubAsync (event T ) {
100118 b .rwMu .RLock ()
101- for topic := range b .subs {
102- go b .subs [topic ].callback (event )
119+
120+ for sub := range b .subs {
121+ go b .subs [sub ].callback (event )
103122 }
123+
104124 b .rwMu .RUnlock ()
105125}
106126
@@ -121,7 +141,7 @@ func (o *Bus[T]) Unsub() {
121141func SubUnsub [T any ](callback func (event T ) bool ) * Bus [T ] {
122142 var (
123143 event T
124- key string
144+ key string
125145 )
126146
127147 switch m := any (event ).(type ) {
@@ -157,7 +177,7 @@ func SubUnsub[T any](callback func(event T) bool) *Bus[T] {
157177func Sub [T any ](callback func (event T )) * Bus [T ] {
158178 var (
159179 event T
160- key string
180+ key string
161181 )
162182
163183 switch m := any (event ).(type ) {
@@ -206,6 +226,7 @@ func Pub[T any](event T) {
206226// PubAsync publishes an event which will be dispatched to all listeners
207227func PubAsync [T any ](event T ) {
208228 var key string
229+
209230 switch m := any (event ).(type ) {
210231 case iEventName :
211232 key = m .EventID ()
0 commit comments