Last active
November 21, 2024 02:12
-
-
Save ValentaTomas/ef71450c9093e9ef61d1d5b23eb31ede to your computer and use it in GitHub Desktop.
Resend the same value to several places without handling subscribers. (Not recommended for production.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Tunnel[T any] struct { | |
ch chan T | |
} | |
func (t *Tunnel[T]) Send(ctx context.Context, value T) error { | |
select { | |
case t.ch <- value: | |
return nil | |
case <-ctx.Done(): | |
return ctx.Err() | |
} | |
} | |
func (t *Tunnel[T]) Recv(ctx context.Context) (T, error) { | |
select { | |
case value := <-t.ch: | |
go func() { | |
t.ch <- value | |
}() | |
return value, nil | |
case <-ctx.Done(): | |
var zero T | |
return zero, ctx.Err() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment