Skip to content

Commit

Permalink
Background refresh only when the new map is not nil
Browse files Browse the repository at this point in the history
  • Loading branch information
Nithin Benny committed Sep 26, 2024
1 parent 5fcff7f commit e01f972
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
6 changes: 5 additions & 1 deletion cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,11 @@ func New(config Config) *Cache {
defer t.Stop()
for {
<-t.C
cache.RefreshCache(config.OnRefresh())
items := config.OnRefresh()
// Only refresh the cache if the items provided is not nil
if items != nil {
cache.RefreshCache(items)
}
}
}()
}
Expand Down
33 changes: 33 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,39 @@ func TestCacheBackgroundRefresh(t *testing.T) {

}

func TestCacheBackgroundRefreshForNilData(t *testing.T) {
count := 0
cache := New(Config{
Capacity: 1,
RefreshInterval: 3 * time.Second,
OnRefresh: func() map[interface{}]interface{} {
count++

if count == 2 {
return nil
}
return map[interface{}]interface{}{"key": count}
},
})

value, ok := cache.Get("key")
assert.Equal(t, true, ok)
assert.Equal(t, 1, value)

time.Sleep(4 * time.Second)

// Prevent refresh when the OnRefresh call back returns nil
value, ok = cache.Get("key")
assert.Equal(t, true, ok)
assert.Equal(t, 1, value)

time.Sleep(4 * time.Second)
value, ok = cache.Get("key")
assert.Equal(t, true, ok)
assert.Equal(t, 3, value)

}

type MockRandGenerator struct {
startAt int64
incr int64
Expand Down

0 comments on commit e01f972

Please sign in to comment.