-
-
Save leonardo5621/c4aaa23fa512762639db0afdcd5253db to your computer and use it in GitHub Desktop.
This file contains 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
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