go - 我如何等待 channel 事件的间歇来触发某些事情?

标签 go debouncing

我有一个 channel ,它将接收对它的突发写入。我想等到 channel 上的突发发送完成后再触发操作。

我看过这个gist , 但是,如果缓冲区中有数据,它将每隔 interval 发送一次输出:

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
}

在我的例子中,我想等到输入 channel 上不再有任何数据在触发或发送输出之前发送到此突发。

我如何实现这一目标?

最佳答案

听起来您需要在 goroutine 之间进行同步,也许沿着这条线。

func main() {

        // Create a channel for our input
        input := make(chan int, 1)
        // Create another for synchronization between main and forked goroutines
        done := make(chan bool)

        go func() {
                // block-wait for received value
                <-input

                // do some more things here

                // when done, send signal to the main goroutine
                done <- true
        }()

        // Do something while wait for the forked goroutine

        // this block until `<-done`
        <-done
        close(mychan)
}

post非常清楚地解释了使用 channel 和同步组进行同步。

关于go - 我如何等待 channel 事件的间歇来触发某些事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979863/

相关文章:

go - 在 Travis CI 自动构建 Go 的提示版本上使用 Godep 时出错

methods - 使用函数名作为参数

go - 创建实现接口(interface)的结构实例的函数

go - 在锁定之前推迟解锁是否可以

javascript - 从事 fetch/axios/debounce 项目

javascript - 对 AJAX 链接的点击进行反跳

go - 在不声明结构的情况下传递接口(interface)对象

ruby-on-rails - 如何创建类似于 javascript throttle/debounce 函数的 Rails/Ruby 方法

apache-kafka - 去抖kafka事件

reactjs - React 功能组件中的 lodash debounce 不起作用