memcast

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2024 License: MIT Imports: 1 Imported by: 0

README

Memcast

A simple, typed, asynchronous in-memory broadcast-subscriber system akin to PubSub but subscribers are limited to a single broadcaster for type safety.

Example

import "gitlab.com/codingpaws/memcast"

func main() {
	broadcaster := memcast.NewBroadcaster[string]()

	subscriber := broadcaster.NewSub()
	defer subscriber.Close()

	broadcaster.Broadcast("hello")

	value := <-subscriber.Ch()
	fmt.Println(value) // prints "hello"
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Broadcaster

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

The broadcaster, created using the NewBroadcaster func.

func NewBroadcaster

func NewBroadcaster[T any]() *Broadcaster[T]

Creates a new broadcaster to which subscribers can register to using the NewSub() method. By broadcasting a message of type T via the Broadcast(T) method, all subscribers will be asynchronously sent the message.

Example
package main

import (
	"fmt"

	"gitlab.com/codingpaws/memcast"
)

func main() {
	broadcaster := memcast.NewBroadcaster[string]()

	subscriber := broadcaster.NewSub()
	defer subscriber.Close()

	broadcaster.Broadcast("hello")

	value := <-subscriber.Ch()
	fmt.Println(value)
}
Output:

hello

func (*Broadcaster[T]) Broadcast

func (self *Broadcaster[T]) Broadcast(value T)

Broadcasts a message of type `T` to all non-closed subscribers.

This method is non-blocking as it notifies each subscriber by creating a goroutine.

func (*Broadcaster[T]) NewSub

func (self *Broadcaster[T]) NewSub() *Subscriber[T]

type Subscriber

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

A subscriber to a broadcaster, created by calling NewSub() on a broadcaster.

func (*Subscriber[T]) Ch

func (self *Subscriber[T]) Ch() <-chan T

Returns a channel from which subscribers can receive messages of type `T`.

The channel will be closed when the subscriber is closed.

func (*Subscriber[T]) Close

func (self *Subscriber[T]) Close()

Closes the subscriber and unregisters it from the broadcaster.

After calling this, the channel returned by Ch() will only return empty strings.

Jump to

Keyboard shortcuts

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