doter1995 2015-04-07 09:17
浏览 11
已采纳

转到属性更改通知

How can you signal 'property' changes to multiple receivers in go?

Similar to how you would define a property in Qt with a notify signal.

E.g. if you imagine having some value that needs to be shown in multiple ways, like a progress value that could be shown both as a progress bar and as textual %, where both would need to update when the underlying value changes.

  • 写回答

1条回答 默认 最新

  • dongrong9938 2015-04-07 10:33
    关注

    One way could to be to utilize channels.

    Your central code which manages/changes the property or variable that needs to be listened may provide a GetChan() function which returns a channel on which modifications (e.g. new values) will be broadcasted:

    // The variable or property that is listened:
    var i int
    
    // Slice of all listeners
    var listeners []chan int
    
    func GetChan() chan int {
        listener := make(chan int, 5)
        listeners = append(listeners, listener)
        return listener
    }
    

    Whenever you change the variable/property, you need to broadcast the change:

    func Set(newi int) {
        i = newi
        for _, ch := range listeners {
            ch <- i
        }
    }
    

    And listeners need to "listen" for change events, which can be done by a for range loop on the channel returned by GetChan():

    func Background(name string, ch chan int, done chan int) {
        for v := range ch {
            fmt.Printf("[%s] value changed: %d
    ", name, v)
        }
        done <- 0
    }
    

    Here is the main program:

    func main() {
        l1 := GetChan()
        l2 := GetChan()
    
        done := make(chan int)
    
        go Background("B1", l1, done)
        go Background("B2", l2, done)
    
        Set(3)
        time.Sleep(time.Second) // Wait a little
        Set(5)
    
        // Close all listeners:
        for _, listener := range listeners {
            close(listener)
        }
    
        // Wait 2 background threads to finish:
        <-done
        <-done
    }
    

    And its output:

    [B1] value changed: 3
    [B2] value changed: 3
    [B1] value changed: 5
    [B2] value changed: 5
    

    You can try the complete program on the Go Playground.

    You may also implement a "broker" which realizes a subscriber model and allows broadcasting messages. See How to broadcast message using channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等