github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/observable/subscriber.go (about)

     1  package observable
     2  
     3  import (
     4  	"os"
     5  )
     6  
     7  type Subscription[T any] <-chan T
     8  
     9  type Subscriber[T any] struct {
    10  	buffer chan T
    11  	done   chan struct{}
    12  }
    13  
    14  func (s *Subscriber[T]) Emit(item T) {
    15  	select {
    16  	case <-s.done:
    17  		return
    18  	default:
    19  	}
    20  	select {
    21  	case s.buffer <- item:
    22  	default:
    23  	}
    24  }
    25  
    26  func (s *Subscriber[T]) Close() error {
    27  	select {
    28  	case <-s.done:
    29  		return os.ErrClosed
    30  	default:
    31  	}
    32  	close(s.done)
    33  	return nil
    34  }
    35  
    36  func (s *Subscriber[T]) Subscription() (subscription Subscription[T], done <-chan struct{}) {
    37  	return s.buffer, s.done
    38  }
    39  
    40  func NewSubscriber[T any](size int) *Subscriber[T] {
    41  	return &Subscriber[T]{
    42  		buffer: make(chan T, size),
    43  		done:   make(chan struct{}),
    44  	}
    45  }