/p/g17khqpukees4237dtn3astzapmp462vjhsz6st4/message
Directory · 4 Files
Message Package
Package provides a simple message broker implementation.
The message broker is a Pub/Sub one. It implements two different interfaces,
Publisher and Subscriber, which are also defined within this package.
Published messages contain the topic where they are published and optional
message data. Subscribing to the TopicAll topic triggers the callback for
messages published to any topic.
Repository can be found at jeronimoalbi/gnome,
as part of jeronimoalbi's Gno smart contracts monorepo.
Usage
1package main
2
3import "gno.land/p/jeronimoalbi/message"
4
5func main() {
6 broker := message.NewBroker()
7
8 // Subscribe to an event
9 subID, err := broker.Subscribe("EventName", func(msg message.Message) {
10 println("EventName has been triggered:", msg.Data.(string))
11 })
12 if err != nil {
13 panic(err)
14 }
15
16 // Publish an event
17 err = broker.Publish("EventName", "Example event data")
18 if err != nil {
19 panic(err)
20 }
21
22 // Unsubscribe from the event
23 unsubscribed, err := broker.Unsubscribe("EventName", subID)
24 if err != nil {
25 panic(err)
26 }
27
28 if !unsubscribed {
29 panic("subscription not found")
30 }
31
32 // Nothing is triggered after unsubscribing
33 err = broker.Publish("EventName", "Ignored event data")
34 if err != nil {
35 panic(err)
36 }
37}
38
39// Output:
40// EventName has been triggered: Example event data