[英]Property change notification in go
How can you signal 'property' changes to multiple receivers in go? 如何在go中向多个接收器发出“属性”变化的信号?
Similar to how you would define a property in Qt with a notify signal. 类似于如何使用通知信号在Qt中定义属性。
Eg 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. 例如,如果您想象某些值需要以多种方式显示,例如可以显示为进度条和文本%的进度值,其中两者都需要在基础值更改时更新。
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 (eg new values) will be broadcasted: 管理/更改需要监听的属性或变量的中央代码可以提供
GetChan()
函数,该函数返回将在其上广播修改(例如新值)的通道:
// 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()
: 并且侦听器需要“监听”更改事件,这可以通过
GetChan()
返回的通道上的for range
循环来完成:
func Background(name string, ch chan int, done chan int) {
for v := range ch {
fmt.Printf("[%s] value changed: %d\n", 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 . 您可以在Go Playground上尝试完整的程序。
You may also implement a "broker" which realizes a subscriber model and allows broadcasting messages. 您还可以实现“代理”,其实现订户模型并允许广播消息。 See How to broadcast message using channel .
请参见如何使用频道广播消息 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.