Skip to content

Instantly share code, notes, and snippets.

@leonardo5621
Last active July 22, 2022 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardo5621/c4aaa23fa512762639db0afdcd5253db to your computer and use it in GitHub Desktop.
Save leonardo5621/c4aaa23fa512762639db0afdcd5253db to your computer and use it in GitHub Desktop.
func takeFirstN(ctx context.Context, dataSource <-chan interface{}, n int) <-chan interface{} {
// 1
takeChannel := make(chan interface{})
// 2
go func() {
defer close(takeChannel)
// 3
for i := 0; i< n; i++ {
select {
case val, ok := <-dataSource:
if !ok{
return
}
takeChannel <- val
case <-ctx.Done():
return
}
}
}()
return takeChannel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment