Skip to content

Instantly share code, notes, and snippets.

@lifei6671
Last active May 30, 2019 05:53
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 lifei6671/9fb3f4ca3b31508697b42e25a7996663 to your computer and use it in GitHub Desktop.
Save lifei6671/9fb3f4ca3b31508697b42e25a7996663 to your computer and use it in GitHub Desktop.
简单事件模拟器
type eventGenerator struct {
eventCh chan int
ctx context.Context
cancel context.CancelFunc
}
func NewEventGenerator(ctx context.Context) *eventGenerator {
// better to get context from others place, even this is a most up level controller
// because you can use `context.Background()` as argument if this is the most up level one
ctx, cancel := context.WithCancel(ctx)
return &eventGenerator{
// don't forget to `make` a channel,
// if you skip it, Go won't give you any warning
// And anything you try to send to it would be ignored!
// No Warning!
eventCh: make(chan int),
ctx: ctx,
cancel: cancel,
}
}
func (e *eventGenerator) Start() {
go func() {
defer close(e.eventCh)
for {
select {
case _, closed := <- e.ctx.Done():
if closed {
return
}
default:
e.eventCh <- 1
}
}
}()
}
func (e *eventGenerator) Events() <-chan int { return e.eventCh }
func (e *eventGenerator) Close() { e.cancel() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment