Categorygithub.com/t2o2/eventbus
modulepackage
0.0.0-20240619063231-e3d760d57cbf
Repository: https://github.com/t2o2/eventbus.git
Documentation: pkg.go.dev

# README

EventBus

GoDoc Coverage Status Build Status

Package EventBus is the little and lightweight eventbus with async compatibility for GoLang.

Installation

Make sure that Go is installed on your computer. Type the following command in your terminal:

go get github.com/asaskevich/EventBus

After it the package is ready to use.

Import package in your project

Add following line in your *.go file:

import "github.com/asaskevich/EventBus"

If you unhappy to use long EventBus, you can do something like this:

import (
	evbus "github.com/asaskevich/EventBus"
)

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);
}

Implemented methods

  • New()
  • Subscribe()
  • SubscribeOnce()
  • HasCallback()
  • Unsubscribe()
  • Publish()
  • SubscribeAsync()
  • SubscribeOnceAsync()
  • SubscribeReplyAsync()
  • Request()
  • WaitAsync()

New()

New returns new EventBus with empty handlers.

bus := EventBus.New();

Subscribe(topic string, fn interface{}) error

Subscribe to a topic. Returns error if fn is not a function.

func Handler() { ... }
...
bus.Subscribe("topic:handler", Handler)

SubscribeOnce(topic string, fn interface{}) error

Subscribe to a topic once. Handler will be removed after executing. Returns error if fn is not a function.

func HelloWorld() { ... }
...
bus.SubscribeOnce("topic:handler", HelloWorld)

Unsubscribe(topic string, fn interface{}) error

Remove callback defined for a topic. Returns error if there are no callbacks subscribed to the topic.

bus.Unsubscribe("topic:handler", HelloWord);

HasCallback(topic string) bool

Returns true if exists any callback subscribed to the topic.

Publish(topic string, args ...interface{})

Publish executes callback defined for a topic. Any additional argument will be transferred to the callback.

func Handler(str string) { ... }
...
bus.Subscribe("topic:handler", Handler)
...
bus.Publish("topic:handler", "Hello, World!");

SubscribeAsync(topic string, fn interface{}, transactional bool)

Subscribe to a topic with an asynchronous callback. Returns error if fn is not a function.

func slowCalculator(a, b int) {
	time.Sleep(3 * time.Second)
	fmt.Printf("%d\n", a + b)
}

bus := EventBus.New()
bus.SubscribeAsync("main:slow_calculator", slowCalculator, false)

bus.Publish("main:slow_calculator", 20, 60)

fmt.Println("start: do some stuff while waiting for a result")
fmt.Println("end: do some stuff while waiting for a result")

bus.WaitAsync() // wait for all async callbacks to complete

fmt.Println("do some stuff after waiting for result")

Transactional determines whether subsequent callbacks for a topic are run serially (true) or concurrently(false)

SubscribeOnceAsync(topic string, args ...interface{})

SubscribeOnceAsync works like SubscribeOnce except the callback to executed asynchronously

SubscribeReplyAsync(topic string, fn interface{})

SubscribeReplyAsync works like SubscribeAsync except the callback is expected to return a value. The value is returned to the caller of Publish.

Request(topic string, handler interface{}, timeoutMs time.Duration, args ...interface{})

Request is a function that allows you to make a request to a topic and wait for a response. The response is returned to the caller of Request as an interface{}.

bus := EventBus.New()

func slowCalculator(reply string, a, b int) {
    time.Sleep(3 * time.Second)
    bus.Publish(reply, a + b)
}

bus.SubscribeReplyAsync("main:slow_calculator", slowCalculator)

reply := bus.Request("main:slow_calculator", func(rslt int) {
    fmt.Printf("Result: %d\n", rslt)
}, 20, 60)

WaitAsync()

WaitAsync waits for all async callbacks to complete.

Cross Process Events

Works with two rpc services:

  • a client service to listen to remotely published events from a server
  • a server service to listen to client subscriptions

server.go

func main() {
    server := NewServer(":2010", "/_server_bus_", New())
    server.Start()
    // ...
    server.EventBus().Publish("main:calculator", 4, 6)
    // ...
    server.Stop()
}

client.go

func main() {
    client := NewClient(":2015", "/_client_bus_", New())
    client.Start()
    client.Subscribe("main:calculator", calculator, ":2010", "/_server_bus_")
    // ...
    client.Stop()
}

Notes

Documentation is available here: godoc.org. Full information about code coverage is also available here: EventBus on gocover.io.

Support

If you do have a contribution for the package feel free to put up a Pull Request or open Issue.

Special thanks to contributors

# Functions

New returns new EventBus with empty handlers.
NewClient - create a client object with the address and server path.
NewNetworkBus - returns a new network bus object at the server address and path.
NewServer - create a new Server at the address and path.

# Constants

PublishService - Client service method.
RegisterService - Server subscribe service method.
No description provided by the author
Subscribe - subscribe to all events.
SubscribeOnce - subscribe to only one event.

# Structs

Client - object capable of subscribing to a remote event bus.
ClientArg - object containing event for client to publish locally.
ClientService - service object listening to events published in a remote event bus.
EventBus - box for handlers and callbacks.
NetworkBus - object capable of subscribing to remote event buses in addition to remote event busses subscribing to it's local event bus.
NetworkBusService - object capable of serving the network bus.
Server - object capable of being subscribed to by remote handlers.
ServerService - service object to listen to remote subscriptions.
SubscribeArg - object to hold subscribe arguments from remote event handlers.
No description provided by the author

# Interfaces

Bus englobes global (subscribe, publish, control) bus behavior.
BusController defines bus control behavior (checking handler's presence, synchronization).
BusPublisher defines publishing-related bus behavior.
BusSubscriber defines subscription-related bus behavior.

# Type aliases

SubscribeType - how the client intends to subscribe.