closer.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. // Package closer provides signaling channel for shutdown
  4. package closer
  5. import (
  6. "context"
  7. )
  8. // Closer allows for each signaling a channel for shutdown
  9. type Closer struct {
  10. ctx context.Context
  11. closeFunc func()
  12. }
  13. // NewCloser creates a new instance of Closer
  14. func NewCloser() *Closer {
  15. ctx, closeFunc := context.WithCancel(context.Background())
  16. return &Closer{
  17. ctx: ctx,
  18. closeFunc: closeFunc,
  19. }
  20. }
  21. // NewCloserWithParent creates a new instance of Closer with a parent context
  22. func NewCloserWithParent(ctx context.Context) *Closer {
  23. ctx, closeFunc := context.WithCancel(ctx)
  24. return &Closer{
  25. ctx: ctx,
  26. closeFunc: closeFunc,
  27. }
  28. }
  29. // Done returns a channel signaling when it is done
  30. func (c *Closer) Done() <-chan struct{} {
  31. return c.ctx.Done()
  32. }
  33. // Err returns an error of the context
  34. func (c *Closer) Err() error {
  35. return c.ctx.Err()
  36. }
  37. // Close sends a signal to trigger the ctx done channel
  38. func (c *Closer) Close() {
  39. c.closeFunc()
  40. }