eventbus

package module
v0.0.0-...-53c5257 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 1, 2019 License: MIT Imports: 1 Imported by: 3

README

eventbus

Yet another Go (golang) eventbus implementation

Installation

Using go get:

go get -u github.com/ispringteam/eventbus

Using dep:

dep ensure -add github.com/ispringteam/eventbus

Usage

First, import this library:

import (
    "github.com/ispringteam/eventbus"
)

Then define your event struct with method EventID() eventbus.EventID:

type solarEclipseEvent struct {
	duration time.Duration
}

func (e *solarEclipseEvent) EventID() EventID {
	return eventSolarEclipse
}

Create the bus (it's better to create bus in the main function) and feel free to Subscribe, Publiish and Unsubscribe:

func main() {
	bus := eventbus.New()
	duration := 100 * time.Second

	id := bus.Subscribe(eventSolarEclipse, func(e Event) {
		se := e.(*solarEclipseEvent)
		fmt.Printf("solar eclipse for %v seconds", se.duration)
	})
	bus.Publish(&solarEclipseEvent{
		duration: duration,
	})
	bus.Unsubscribe(id);
}

Why yet another EventBus?

This package is inspired by github.com/asaskevich/EventBus, but has differences:

  • no event bus over network, no async event bus: only process-local synchronous event handlers are supported
  • events identified by EventID instead of string
  • Unsubscribe() accepts unique subscription ID instead of event name and callback
  • no deadlocks anymore: this eventbus doesn't lock mutex while calling external code

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bus

type Bus interface {
	BusSubscriber
	BusPublisher
}

Bus allows to subscribe/unsubscribe to external events and publish own events

func New

func New() Bus

New returns new event bus

type BusPublisher

type BusPublisher interface {
	Publish(event Event)
}

BusPublisher allows to publish own events

type BusSubscriber

type BusSubscriber interface {
	Subscribe(eventID EventID, cb EventHandler) Subscription
	Unsubscribe(id Subscription)
}

BusSubscriber allows to subscribe/unsubscribe own event handlers

type Event

type Event interface {
	EventID() EventID
}

Event must be implemented by anything that can be published

type EventHandler

type EventHandler func(event Event)

EventHandler is function that can be subscribed to the event

type EventID

type EventID string

EventID identifies events topic.

type Subscription

type Subscription struct {
	// contains filtered or unexported fields
}

Subscription represents active event subscription

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL