github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/stream/typed.go (about)

     1  package stream
     2  
     3  import "github.com/asynkron/protoactor-go/actor"
     4  
     5  type TypedStream[T any] struct {
     6  	c           chan T
     7  	pid         *actor.PID
     8  	actorSystem *actor.ActorSystem
     9  }
    10  
    11  func (s *TypedStream[T]) C() <-chan T {
    12  	return s.c
    13  }
    14  
    15  func (s *TypedStream[T]) PID() *actor.PID {
    16  	return s.pid
    17  }
    18  
    19  func (s *TypedStream[T]) Close() {
    20  	s.actorSystem.Root.Stop(s.pid)
    21  	close(s.c)
    22  }
    23  
    24  func NewTypedStream[T any](actorSystem *actor.ActorSystem) *TypedStream[T] {
    25  	c := make(chan T)
    26  
    27  	props := actor.PropsFromFunc(func(ctx actor.Context) {
    28  		switch msg := ctx.Message().(type) {
    29  		case actor.AutoReceiveMessage, actor.SystemMessage:
    30  		// ignore terminate
    31  		case T:
    32  			c <- msg
    33  		}
    34  	})
    35  	pid := actorSystem.Root.Spawn(props)
    36  
    37  	return &TypedStream[T]{
    38  		c:           c,
    39  		pid:         pid,
    40  		actorSystem: actorSystem,
    41  	}
    42  }