Last active
May 30, 2019 05:53
-
-
Save lifei6671/9fb3f4ca3b31508697b42e25a7996663 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
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