broadcaster

package module
v0.0.0-...-743d897 Latest Latest
Warning

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

Go to latest
Published: May 22, 2020 License: MIT Imports: 2 Imported by: 0

README

broadcaster

GoDoc Build Status

A small golang library for broadcasting a message to many subscribers

To install, run go get github.com/stvnrhodes/broadcaster

Documentation

Overview

Package broadcaster allows broadcasting a value over many channels at once.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Caster

type Caster interface {
	// Subscribe will return a channel that recieves broadcasted messages, along
	// with a done channel that unsubscribes and closes the broadcast channel
	// when closed. When unsubscribing, any messages currently pending will still
	// still be attempting to send until after the WaitTime.
	Subscribe(done <-chan struct{}) <-chan interface{}
	// Cast sends a message to be broadcast to all subscribers.
	Cast(msg interface{})
	// Close closes all created channels. Further calls to Close or Cast will
	// panic, and further subscriptions will return a closed channel.
	Close()
}

Caster allows sending messages to many subscribed channels.

Example
package main

import (
	"fmt"
	"sync"

	"github.com/stvnrhodes/broadcaster"
)

func main() {
	// Create a new broadcaster
	b := broadcaster.New()

	// Create a channel subscribed to the broadcaster
	done := make(chan struct{})
	ch := b.Subscribe(done)

	// Wait groups are added to make the example more deterministic.
	// In most cases, having no wait groups is fine.
	var wg, wg2 sync.WaitGroup
	wg.Add(1)
	wg2.Add(1)

	// Read all messages from the channel.
	go func() {
		for msg := range ch {
			fmt.Println("Hello", msg)
		}
		wg.Done()
	}()

	b.Cast("World")

	// Create another channel. This one won't unsubscribe, so the argument is nil.
	ch2 := b.Subscribe(nil)

	// Read all messages from the channel.
	go func() {
		for msg := range ch2 {
			fmt.Println("Goodbye", msg)
		}
		wg2.Done()
	}()

	// Cast to the channel
	b.Cast(123)
	close(done)
	wg.Wait()
	b.Cast("examples")
	b.Close()
	wg2.Wait()
}
Output:
Hello World
Hello 123
Goodbye 123
Goodbye examples

func New

func New(opts ...*Options) Caster

New creates a new broadcaster that broadcasts a message to many subscribers. If multiple options are supplied, only the first one is considered.

type Options

type Options struct {
	// Time to wait on a subscriber's channel before giving up. Default is 1s.
	WaitTime time.Duration
}

Options allows specifying additional options when creating a broadcaster.

Jump to

Keyboard shortcuts

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