Using Go Subroutine with external Events

Wanted to validate a pattern for which includes events and goroutines.Question is - is it a good approach to call event running in the main loop from go subroutine. Consider the following example

https://play.golang.org/p/PpBfXG34GN8

package main

import (
"fmt"

"github.com/asaskevich/EventBus"
)

type SomeRandomState struct {
GlobalBusObj EventBus.Bus
}

func NewRandomState() *SomeRandomState {
return &SomeRandomState{
	GlobalBusObj: EventBus.New(),
}

}

func GlobalEventBusMessageReceived(msg string) {
fmt.Println("Message Received to Global Bus:" + msg)
}
func main() {
done := make(chan bool)

fmt.Println("Hello, playground")

s := NewRandomState()
s.GlobalBusObj.Subscribe("message_to_global_event_bus", GlobalEventBusMessageReceived)
s.GlobalBusObj.Publish("message_to_global_event_bus", "Publishing msg:Hello World") //the 
publishing of event works fine

go func() {
	fmt.Println("Inside go subrountine")
	s.GlobalBusObj.Publish("message_to_global_event_bus", "This is msg from the subroutine") 
//is this a good idea to send msg via events from a go subroutine to the main subroutine?

	done <- true
}()

<-done

}
2 Likes

This seam to make sense to me. I would say it is a valid use.

It also can’t be easily replaced by channels because there might be multiple subscribers to the same event bus.

3 Likes

Thanks @Christophe_Meessen

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.