Documentation ¶
Overview ¶
Package notify contains utility code for notification behaviors.
Index ¶
- Variables
- type Var
- func (v *Var[T]) Get() (T, <-chan struct{})
- func (v *Var[T]) Notify()
- func (v *Var[T]) Peek(fn func(value T) error) (<-chan struct{}, error)
- func (v *Var[T]) Set(next T) <-chan struct{}
- func (v *Var[T]) Swap(next T) (T, <-chan struct{})
- func (v *Var[T]) Update(fn func(old T) (new T, _ error)) (T, <-chan struct{}, error)
Constants ¶
This section is empty.
Variables ¶
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 (*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 ¶
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]) Swap ¶
func (v *Var[T]) Swap(next T) (T, <-chan struct{})
Swap returns the current value and a channel that will be closed when the next value has been replaced.
func (*Var[T]) Update ¶
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.