events

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2022 License: MIT Imports: 2 Imported by: 3

README

events Go license codecov PkgGoDev

简单的事件订阅发布系统

e := events.New[string]()

e.Attach(sub1)
e.Attach(sub2)

e.Publish(true, "触发事件1") // sub1 和 sub2 均会收事事件

安装

go get github.com/issue9/events

版权

本项目采用 MIT 开源授权许可证,完整的授权说明可在 LICENSE 文件中找到。

Documentation

Overview

Package events 提供了简单的事件发布订阅功能

e := events.New[string]()

// 订阅事件
e.Attach(func(data string){
    fmt.Println("subscriber 1:", data)
})

// 订阅事件
e.Attach(func(data string){
    fmt.Println("subscriber 2:", data)
})

e.Publish(true, "test") // 发布事件

Index

Constants

This section is empty.

Variables

View Source
var ErrStopped = errors.New("该事件已经停止发布新内容")

ErrStopped 表示发布都已经调用 [Publisher.Destroy] 销毁了事件处理器

Functions

This section is empty.

Types

type Eventer added in v0.2.0

type Eventer[T any] interface {
	Publisher[T]
	Subscriber[T]
}

func New

func New[T any]() Eventer[T]

New 声明一个新的事件处理

T 为事件传递过程的参数类型;

type Publisher

type Publisher[T any] interface {
	// Publish 触发事件
	//
	// sync 表示订阅者是否以异步的方式执行;
	// data 传递给订阅者的数据;
	Publish(sync bool, data T) error

	// Destroy 销毁当前事件处理程序
	Destroy()
}

Publisher 事件的发布者

type SubscribeFunc added in v0.6.0

type SubscribeFunc[T any] func(data T)

SubscribeFunc 订阅者函数

每个订阅函数都是通过 go 异步执行。

data 为事件传递过来的数据,可能存在多个订阅者, 用户不应该直接修改 data 数据,否则结果是未知的。

type Subscriber

type Subscriber[T any] interface {
	// Attach 注册订阅者
	//
	// 返回唯一 ID,用户可以使用此 ID 取消订阅。
	Attach(SubscribeFunc[T]) (int, error)

	// Detach 取消指定事件的订阅
	Detach(int)
}

Subscriber 供用户订阅事件的对象接口

Jump to

Keyboard shortcuts

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