go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/simutil/read_events.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  // EventHandler is a method that receives events from `EventHandle`.
    13  type EventHandler[T any] func(context.Context, Event[T])
    14  
    15  // ReadEvents reads from a given event channel and calls a given handler function for each event.
    16  func ReadEvents[T any](ctx context.Context, from <-chan Event[T], to EventHandler[T]) {
    17  	go func() {
    18  		var e Event[T]
    19  		for {
    20  			select {
    21  			case <-ctx.Done():
    22  				return
    23  			case e = <-from:
    24  				to(ctx, e)
    25  			}
    26  		}
    27  	}()
    28  }