notify

package
v0.0.0-...-4dcfcdd Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package notify contains utility code for notification behaviors.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoUpdate = errors.New("no update required")

ErrNoUpdate is a sentinel value that can be returned by the callback passed to Var.Update.

Functions

This section is empty.

Types

type Var

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

A Var holds a value that can be set or retrieved. It also provides a channel that indicates when the value has changed.

Usage notes:

  • The zero value of Var is ready to use.
  • Var can be called concurrently from multiple goroutines.
  • A Var should not be copied.
  • If the value contained by the Var is mutable, the Var.Peek and Var.Update methods should be used to ensure race-free behavior.

func VarOf

func VarOf[T any](initial T) *Var[T]

VarOf constructs a Var set to the initial value.

func (*Var[T]) Get

func (v *Var[T]) Get() (T, <-chan struct{})

Get returns the current (possibly zero) value for T and a channel that will be closed the next time that Set or Update is called. This API does not guarantee that a loop as shown below will see every update made to the Var. Rather, it allows a consumer to sample the most current value available.

for value, valueUpdated := v.Get(); ;{
  doSomething(value)
  select {
    case <-valueUpdated:
      value, valueUpdated = v.Get()
    case <-ctx.Done():
      return ctx.Err()
  }
}

func (*Var[T]) Notify

func (v *Var[T]) Notify()

Notify behaves as though Set was called with the current value. That is, it replaces the notification channel.

func (*Var[T]) Peek

func (v *Var[T]) Peek(fn func(value T) error) (<-chan struct{}, error)

Peek holds a read lock while the callback is invoked. This method will return the notification channel associated with the current value of the Var.

func (*Var[T]) Set

func (v *Var[T]) Set(next T) <-chan struct{}

Set updates the value and notifies any listeners. The notification channel is returned to avoid a race condition if a caller wants to set the value and receive a notification if another caller has subsequently updated it.

func (*Var[T]) Update

func (v *Var[T]) Update(fn func(old T) (new T, _ error)) (T, <-chan struct{}, error)

Update atomically updates the stored value using the current value as an input. The callback may return ErrNoUpdate to take no action; this error will not be returned to the caller. If the callback returns any other error, no action is taken and the unchanged value is returned.

Jump to

Keyboard shortcuts

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