Issue
I am trying to learn GO and in doing so trying different concepts. Right now I am trying a PubSub approach, but within the application. I have an EventBus and I amd trying to pass the instance via Dependency Injection. However when I run the application nothing happens.
main
package main
import (
"github.com/asaskevich/EventBus"
modelA "interfaces/internal/modelA"
modelB "interfaces/internal/modelB"
)
func main() {
bus := EventBus.New()
a := &modelA.Bus{EventBus: bus}
a.Send()
b := &modelB.Bus{
EventBus: bus,
}
b.Receive()
}
internal/modelA
package modelA
import (
"fmt"
"github.com/asaskevich/EventBus"
)
type Bus struct {
EventBus EventBus.Bus
}
type ModelAService interface {
Run()
Send()
}
func calculator(a int, b int) {
fmt.Printf("ModelA "+"%d\n", a+b)
}
func (bus *Bus) Receive() {
err := bus.EventBus.Subscribe("testMessageFromB", calculator)
if err != nil {
fmt.Printf("Error Receiving message...")
}
}
func (bus *Bus) Send() {
bus.EventBus.Publish("testMessageFromA", 33, 33)
}
internal/modelB
package modelB
import (
"fmt"
"github.com/asaskevich/EventBus"
)
type Bus struct {
EventBus EventBus.Bus
}
type ModelBService interface {
Run()
Send()
}
func calculator(a int, b int) {
fmt.Printf("ModelB "+"%d\n", a+b)
}
func (bus *Bus) Receive() {
err := bus.EventBus.Subscribe("testMessageFromA", calculator)
if err != nil {
fmt.Printf("Error Receiving message...")
}
}
func (bus *Bus) Send() {
bus.EventBus.Publish("testMessageFromB", 33, 60)
}
Solution
You need to first Subscribe to a topic
then Publish (executes callback defined for a topic).
Try something like this:
func main() {
bus := EventBus.New()
a := &modelA.Bus{EventBus: bus}
b := &modelB.Bus{EventBus: bus}
b.Receive() // Subscribe
a.Send() // Publish
// Unsubscribe
}
Also see the example:
func calculator(a int, b int) {
fmt.Printf("%d\n", a + b)
}
func main() {
bus := EventBus.New();
bus.Subscribe("main:calculator", calculator);
bus.Publish("main:calculator", 20, 40);
bus.Unsubscribe("main:calculator", calculator);
}
My debugging structure and output:
Footnotes:
You may rename b.Receive()
to b.Subscribe()
and a.Send()
to a.Publish()
for clarity.
See also gRPC:
Answered By – wasmup
Answer Checked By – Robin (GoLangFix Admin)