notifier.go 828 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package signal
  2. import "io"
  3. // Notifier is a utility for notifying changes. The change producer may notify changes multiple time, and the consumer may get notified asynchronously.
  4. type Notifier struct {
  5. c chan struct{}
  6. }
  7. // NewNotifier creates a new Notifier.
  8. func NewNotifier() *Notifier {
  9. return &Notifier{
  10. c: make(chan struct{}, 1),
  11. }
  12. }
  13. // Signal signals a change, usually by producer. This method never blocks.
  14. func (n *Notifier) Signal() {
  15. select {
  16. case n.c <- struct{}{}:
  17. default:
  18. }
  19. }
  20. // Wait returns a channel for waiting for changes. The returned channel never gets closed.
  21. func (n *Notifier) Wait() <-chan struct{} {
  22. return n.c
  23. }
  24. type nCloser struct {
  25. n *Notifier
  26. }
  27. func (c *nCloser) Close() error {
  28. c.n.Signal()
  29. return nil
  30. }
  31. func NotifyClose(n *Notifier) io.Closer {
  32. return &nCloser{
  33. n: n,
  34. }
  35. }