Skip to content

Commit

Permalink
fix onchanged listener
Browse files Browse the repository at this point in the history
  • Loading branch information
Yohan Totting committed Nov 29, 2023
1 parent 1892d23 commit 0814f95
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
14 changes: 7 additions & 7 deletions meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ func NewMetadata() *Metadata {

func (m *Metadata) Set(key string, value interface{}) {
m.mu.Lock()
defer m.mu.Unlock()

m.m[key] = value
m.mu.Unlock()

m.onChanged(key, value)
}

Expand All @@ -44,9 +44,9 @@ func (m *Metadata) Get(key string) (interface{}, error) {

func (m *Metadata) Delete(key string) {
m.mu.Lock()
defer m.mu.Unlock()

delete(m.m, key)
m.mu.Unlock()

m.onChanged(key, nil)
}

Expand All @@ -67,17 +67,17 @@ func (m *Metadata) onChanged(key string, value interface{}) {

func (m *Metadata) OnChanged(ctx context.Context, f func(key string, value interface{})) {
m.mu.Lock()
defer m.mu.Unlock()

nextIdx := len(m.onChangedCallbacks)
m.onChangedCallbacks = append(m.onChangedCallbacks, f)
m.mu.Unlock()

go func() {
localCtx, cancel := context.WithCancel(ctx)
defer cancel()

<-localCtx.Done()

m.mu.Lock()
defer m.mu.Unlock()
for i, _ := range m.onChangedCallbacks {
if nextIdx == i {
m.onChangedCallbacks = append(m.onChangedCallbacks[:i], m.onChangedCallbacks[i+1:]...)
Expand Down
20 changes: 19 additions & 1 deletion meta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func TestMetadata(t *testing.T) {

// Test OnChanged method
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

ch := make(chan struct{})
m.OnChanged(ctx, func(key string, value interface{}) {
t.Logf("Key: %s, Value: %v", key, value)
Expand All @@ -53,4 +53,22 @@ func TestMetadata(t *testing.T) {
}()

<-ch

// cancel the listener above
cancel()

// Test OnChanged method with cancel
var state = true
ctx1, cancel1 := context.WithCancel(context.Background())
m.OnChanged(ctx1, func(key string, value interface{}) {
t.Logf("Key: %s, Value: %v", key, value)
state = false
})

cancel1()

m.Set("key6", "value6")

require.Equal(t, true, state)

}

0 comments on commit 0814f95

Please sign in to comment.