go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/simutil/event_pipe.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package simutil
     9  
    10  import "context"
    11  
    12  // EventPipe pipes events from one channel to another with a background goroutine
    13  // that can be canceled with the given context.
    14  func EventPipe[T any](ctx context.Context, from <-chan Event[T], to chan Event[T]) {
    15  	go func() {
    16  		var e Event[T]
    17  		for {
    18  			select {
    19  			case <-ctx.Done():
    20  				return
    21  			case e = <-from:
    22  				select {
    23  				case <-ctx.Done():
    24  					return
    25  				case to <- e:
    26  					continue
    27  				}
    28  			}
    29  		}
    30  	}()
    31  }