event

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2022 License: MIT Imports: 0 Imported by: 0

README

Simple Event PubSub Support

Event driven is quite important in some cases. Unfortunately, if you google around, there is no recommended "Event" solution for go project (There is one in ethereum project, but you don't want to clone the whole ethereum codebase just for event package...).
One of the reasons is because go channel is fundamentally simliar to "event", which you can send and receive message in different gorountines. So it's not very difficult to implement even-alike pub/sub support.

However, it's still taking time to do so and pretty error prone. Then I made this simple implementing as part of skema-go framework for you to use. In skema-go itself, the event package is use in data/dao for notifying elasticsearch to update indexes.

The usage is simple, you can check event_test.go for details. Here is how you subscribe to an event and notify through publish:

	i := 0
	pubsub := event.NewPubSub()

	end := make(chan int)
	f := func(v interface{}) {
		fmt.Printf("get value %d\n", v.(int))
		i = v.(int)
	}

    e1 := pubsub.Subscribe("test", f)	// create subscription (a.k.a. listener)
    pubsub.Subscribe("get", func(interface{}) {
		end <- i
	})

	for k := 0; k < 5; k++ {
		pubsub.Publish("test", k)      // Publish data (send to the listener)
	}

	pubsub.Publish("get", 0)           // notify another subscriber to retrieve value (send to chan variable end)
	result = <-end                     // get the value
	assert.Equal(t, 4, result)

	pubsub.Unsubscribe("test", e1)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EventHandler

type EventHandler func(interface{})

type PubSub

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

func NewPubSub

func NewPubSub() *PubSub

func (*PubSub) Publish

func (p *PubSub) Publish(eventName string, msg interface{})

publish an event by given name

func (*PubSub) Subscribe

func (p *PubSub) Subscribe(eventName string, h EventHandler) chan interface{}

Subscribe to an event with a function handler return the channel in case you need to unsubscribe leater

func (*PubSub) Unsubscribe

func (p *PubSub) Unsubscribe(eventName string, ch chan interface{})

Unsubscribe an event, by giving the chan object created when subscribing

Jump to

Keyboard shortcuts

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