I am trying to figure out if there is a way to debounced a struct map that is group by an id.
Using the following struct for this example:
type Message struct {
id int
attrs []string
}
This is how I am creating the list
messages := []Message{
Message{
id: 10,
attrs: []string{"blah", "foo"},
},
Message{
id: 10,
attrs: []string{"add", "ddsds"},
},
Message{
id: 11,
attrs: []string{"foo", "bar"},
},
Message{
id: 12,
attrs: []string{"xyz"},
},
}
And then turning into a map grouped by id:
collections := make(map[int][]Message)
for _, j := range messages {
collections[j.id] = append(collections[j.id], j)
}
This is the main function:
debounced := debounce.New(100 * time.Millisecond)
for _, messageMap := range collections {
for _, message := range messageMap {
debounced(func() {
fmt.Println("id", message.id, "attrs =>", message.attrs)
})
}
}
time.Sleep(500 * time.Millisecond)
The output is:
id 12 attrs => [xyz]
This is not correct. And it looks like it just getting the last message.
CodePudding user response:
I got it to work. I just need to wait after the first loop:
debounced := debounce.New(100 * time.Millisecond)
for _, messageMap := range collections {
for _, message := range messageMap {
message := message // Copy the loop var
debounced(func() {
fmt.Println("id", message.id, "attrs =>", message.attrs)
})
}
time.Sleep(500 * time.Millisecond)
}
CodePudding user response:
With the closure you are capturing the loop variable, which is rewritten for every iteration. Capture a copy of it:
for _, message := range messageMap {
message:=message // Copy the loop var
debounced(func() {
fmt.Println("id", message.id, "attrs =>", message.attrs)
})
}