| | 1 | | using System.Collections; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using UnityEngine; |
| | 4 | |
|
| | 5 | | public class DataCache<T> : IDataCache<T> |
| | 6 | | { |
| | 7 | | private class CacheType |
| | 8 | | { |
| | 9 | | public T value; |
| | 10 | | public float lastUpdate; |
| | 11 | | public float maxAge; |
| | 12 | | public Coroutine expireCacheRoutine; |
| | 13 | | } |
| | 14 | |
|
| 144 | 15 | | private readonly Dictionary<string, CacheType> cache = new Dictionary<string, CacheType>(); |
| | 16 | |
|
| | 17 | | public void Add(string key, T value, float maxAge) |
| | 18 | | { |
| 0 | 19 | | if (cache.TryGetValue(key, out CacheType storedCache)) |
| | 20 | | { |
| 0 | 21 | | CoroutineStarter.Stop(storedCache.expireCacheRoutine); |
| 0 | 22 | | } |
| | 23 | | else |
| | 24 | | { |
| 0 | 25 | | storedCache = new CacheType(); |
| 0 | 26 | | cache[key] = storedCache; |
| | 27 | | } |
| | 28 | |
|
| 0 | 29 | | storedCache.value = value; |
| 0 | 30 | | storedCache.maxAge = maxAge; |
| 0 | 31 | | storedCache.lastUpdate = Time.unscaledTime; |
| 0 | 32 | | storedCache.expireCacheRoutine = CoroutineStarter.Start(RemoveCache(key, storedCache.maxAge)); |
| 0 | 33 | | } |
| | 34 | |
|
| | 35 | | public bool TryGet(string key, out T value, out float lastUpdate) |
| | 36 | | { |
| 0 | 37 | | value = default(T); |
| 0 | 38 | | lastUpdate = 0; |
| | 39 | |
|
| 0 | 40 | | if (cache.TryGetValue(key, out CacheType storedCache)) |
| | 41 | | { |
| 0 | 42 | | value = storedCache.value; |
| 0 | 43 | | lastUpdate = storedCache.lastUpdate; |
| 0 | 44 | | return true; |
| | 45 | | } |
| | 46 | |
|
| 0 | 47 | | return false; |
| | 48 | | } |
| | 49 | |
|
| | 50 | | public void Forget(string key) |
| | 51 | | { |
| 0 | 52 | | if (cache.TryGetValue(key, out CacheType storedCache)) |
| | 53 | | { |
| 0 | 54 | | CoroutineStarter.Stop(storedCache.expireCacheRoutine); |
| 0 | 55 | | cache.Remove(key); |
| | 56 | | } |
| 0 | 57 | | } |
| | 58 | |
|
| | 59 | | public void Dispose() |
| | 60 | | { |
| 144 | 61 | | using (var iterator = cache.GetEnumerator()) |
| | 62 | | { |
| 144 | 63 | | while (iterator.MoveNext()) |
| | 64 | | { |
| 0 | 65 | | CoroutineStarter.Stop(iterator.Current.Value.expireCacheRoutine); |
| | 66 | | } |
| 144 | 67 | | } |
| | 68 | |
|
| 144 | 69 | | cache.Clear(); |
| 144 | 70 | | } |
| | 71 | |
|
| | 72 | | private IEnumerator RemoveCache(string key, float delay) |
| | 73 | | { |
| 0 | 74 | | yield return WaitForSecondsCache.Get(delay); |
| 0 | 75 | | cache?.Remove(key); |
| 0 | 76 | | } |
| | 77 | | } |