From e01f972369a6715bb92ee398c7a1e32b87028151 Mon Sep 17 00:00:00 2001 From: Nithin Benny Date: Thu, 26 Sep 2024 12:11:20 +0530 Subject: [PATCH] Background refresh only when the new map is not nil --- cache.go | 6 +++++- cache_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/cache.go b/cache.go index 8539acd..f3c1f8b 100644 --- a/cache.go +++ b/cache.go @@ -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) + } } }() } diff --git a/cache_test.go b/cache_test.go index 2069f5a..1dd971f 100644 --- a/cache_test.go +++ b/cache_test.go @@ -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