keyeddistributor

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2024 License: MIT Imports: 2 Imported by: 1

README

keyeddistributor - distribute events to listeners by key

GoDoc unit tests report card codecov

Install:

go get github.com/memsql/keyeddistributor

Keyeddistributor is an add-on to eventdistributor that allows for ad-hoc subscription to events that match a key value.

An example

keyed := keyeddistributor.New(func(t Thing) ThingKey) {
	return t.Key // or whatever is needed to extract a ThingKey from a Thing
})

reader := keyed.Subscribe("some key value")
defer reader.Unsubscribe()

<-reader.WaitChan()
thing := reader.Consume()
// do stuff with thing

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Distributor

type Distributor[E any, K comparable] struct {
	// contains filtered or unexported fields
}

Distributor supports subscribing to get a Reader

func New

func New[E any, K comparable](key func(E) K) *Distributor[E, K]

func (*Distributor[E, K]) Submit

func (k *Distributor[E, K]) Submit(e E) <-chan struct{}

Submit pushes an event into the Distributor. The returned channel is closed when the event has been fully consumed. If there are no subscribers, the event will be considered consumed immediately.

Submit is thread-safe

func (*Distributor[E, K]) Subscribe

func (k *Distributor[E, K]) Subscribe(value K) *Reader[E]

Subscribe creates a Reader that listens for events where the key matches a specific value. It is recommended that immediately after a Subscribe, that you defer the Unsubscribe:

reader := distributor.Subscribe(someValue)
defer reader.Unsubscribe()

Subscribe is thread-safe

type Reader

type Reader[E any] struct {
	eventdistributor.Reader[E]
	// contains filtered or unexported fields
}

Reader is used by a single subscriber to get events. Select on reader.WaitChan() to know when there is an event ready to consume and then use reader.Consume() to get the event. Use reader.Unsubscribe() when the reader is no longer needed. Reader embeds eventdistributor's Reader.

func (*Reader[E]) Unsubscribe

func (r *Reader[E]) Unsubscribe()

Unsubscribe releases a Reader. After an Unsubscribe, the WaitChan() and Consume() methods should not be used. It is important to Unsubscribe() because otherwise the Distributor will keep buffering events that are meant for the reader.

Jump to

Keyboard shortcuts

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