typedsf

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2023 License: Apache-2.0 Imports: 2 Imported by: 1

README

go-typed-singleflight

Generic-supporting golang.org/x/sync/singleflight.

Example usage (Go Playground):

package main

import (
	"fmt"
	"sync"
	"time"

	typedsf "github.com/t2bot/go-typed-singleflight"
)

type MyValue string

func main() {
	g := new(typedsf.Group[MyValue])

	workFn := func() (MyValue, error) {
		// for example purposes only, sleep for a moment
		time.Sleep(1 * time.Second)
		return MyValue("this is a value"), nil
	}

	key := "my_resource" // deduplication key

	// This loop simulates multiple requests
	wg := new(sync.WaitGroup)
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			val, err, shared := g.Do(key, workFn)
			if err != nil {
				panic(err)
			}

			if shared {
				fmt.Println("Response was shared!")
				// When true, the workFn was only called once and its output used
				// multiple times.
			} else {
				// This might happen - it's dependent on the underlying singleflight
				// library behaviour.
				fmt.Println("WARN: Response was not shared!")
			}

			fmt.Println("Got val: ", val)
		}()
	}

	fmt.Println("Waiting for all requests to finish")
	wg.Wait()
	fmt.Println("Done!")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

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

Group is the same as singleflight.Group, but with type information

func (*Group[T]) Do

func (g *Group[T]) Do(key string, fn func() (T, error)) (T, error, bool)

Do is the same as singleflight.Group, but with type information. If for some reason an incorrect type is returned by `fn` then an error will be returned to all callers.

func (*Group[T]) DoChan

func (g *Group[T]) DoChan(key string, fn func() (T, error)) <-chan Result[T]

DoChan is the same as singleflight.Group, but with type information. If for some reason an incorrect type is returned by `fn` then an error will be returned to all callers via the channel.

The returned channel is not closed.

func (*Group[T]) Forget

func (g *Group[T]) Forget(key string)

Forget is the same as singleflight.Group

type Result

type Result[T any] struct {
	Val    T
	Err    error
	Shared bool
}

Result is the same as singleflight.Result, but with type information

Jump to

Keyboard shortcuts

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