我有一个通道会收到大量的写入。我想等到通道上的一系列发送完成后再触发操作。
我看过这个gistinterval
,但是,如果缓冲区中有数据,它将在输出上发送:
func debounceChannel(interval time.Duration, output chan int) chan int {
input := make(chan int)
go func() {
var buffer int
var ok bool
// We do not start waiting for interval until called at least once
buffer, ok = <-input
// If channel closed exit, we could also close output
if !ok {
return
}
// We start waiting for an interval
for {
select {
case buffer, ok = <-input:
// If channel closed exit, we could also close output
if !ok {
return
}
case <-time.After(interval):
// Interval has passed and we have data, so send it
output <- buffer
// Wait for data again before starting waiting for an interval
buffer, ok = <-input
if !ok {
return
}
// If channel is not closed we have more data and start waiting for interval
}
}
}()
return input
}
就我而言,我想等到输入通道上不再有任何数据发送到此突发,然后再触发或发送到输出。
我如何实现这一目标?