events

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 3 Imported by: 2

README

events Go license codecov PkgGoDev

简单的事件订阅发布系统

e := events.New[string]()

e.Subscribe(sub1)
e.Subscribe(sub2)

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

安装

go get github.com/issue9/events

版权

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

Documentation

Overview

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

e := events.New[string]()

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

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

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Event

type Event[T any] struct {
	// contains filtered or unexported fields
}

Event 事件处理对象

同时实现了 SubscriberPublisher 两个接口。

func New

func New[T any]() *Event[T]

New 声明一个新的事件处理

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

func (*Event[T]) Len added in v0.9.0

func (e *Event[T]) Len() (c int)

Len 订阅者的数量

func (*Event[T]) Publish added in v0.8.0

func (e *Event[T]) Publish(sync bool, data T)

func (*Event[T]) Reset added in v0.8.0

func (e *Event[T]) Reset()

Reset 重置对象

func (*Event[T]) Subscribe added in v0.8.0

func (e *Event[T]) Subscribe(subscriber SubscribeFunc[T]) context.CancelFunc

type Publisher

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

Publisher 事件的发布者

type SubscribeFunc added in v0.6.0

type SubscribeFunc[T any] func(data T)

SubscribeFunc 订阅者函数

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

type Subscriber

type Subscriber[T any] interface {
	// Subscribe 注册订阅事件
	//
	// 返回用于注销此订阅事件的方法。
	Subscribe(SubscribeFunc[T]) context.CancelFunc
}

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

Jump to

Keyboard shortcuts

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