typevent

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2023 License: MIT Imports: 1 Imported by: 0

README

typevent

Unit Tests Go Reference

typevent provides type-safe event messaging channels for Go. They can be used to implement Pub/Sub schemes without the need for type assertions, streamlining the application code that uses the event channels.

At the core it consists of a generic Channel interface with the following methods:

type Channel[E Event] interface {
    // Emit emits an event of type E on the channel.
    Emit(E) error
    // Subscribe registers a handler for events of type E on the channel.
    Subscribe(ctx context.Context, handler Handler[E]) (Subscription, error)
}

The package currently provides one implementation of the interface, using Redis Pub/Sub as the backing distribution system. Usage can look as follows:

import (
    "context"
    "fmt"

    redisclient "github.com/redis/go-redis/v9"
    "github.com/sehrgutesoftware/typevent/redis"
)

func ExampleNewChannel() {
    type event string

    // Create a new channel using redis Pub/Sub as the underlying event bus.
    client := redisclient.NewClient(&redisclient.Options{Addr: "localhost:6379"})

    // conf holds the redis client used by the channel
    conf := redis.NewConfig(client)

    // This is where we create the channel that can be used to emit and subscribe to events
    channel := redis.NewChannel[event](conf, "CHANNEL_NAME")

    // Register a subscriber for the channel.
    sub, _ := channel.Subscribe(context.Background(), func(ctx context.Context, ev event) error {
        fmt.Printf("subscriber says: %s\n", ev)
        return nil
    })
    defer sub.Close()

    // Emit an event on the channel.
    channel.Emit("Hello World!")
}

Development

Run Tests
go test ./...

Documentation

Overview

Package typevent provides type safe event channels.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Channel

type Channel[E Event] interface {
	// Emit emits an event of type E on the channel.
	Emit(E) error
	// Subscribe registers a handler for events of type E on the channel.
	Subscribe(ctx context.Context, handler Handler[E]) (Subscription, error)
}

Channel is an event channel that can emit and subscribe to events of a specific type.

See [typevent.redis.NewChannel] for an example implementation.

type Event

type Event any

Event is an event that can be emitted on an event channel.

type Handler

type Handler[E Event] func(context.Context, E) error

Handler is a function that handles an event of a specific type.

type Subscription

type Subscription interface {
	// Close unsubscribes from the channel.
	Close() error
}

Subscription is a subscription to an event channel.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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