Skip to content

Instantly share code, notes, and snippets.

@wallstop
Created March 15, 2022 01:12
Show Gist options
  • Save wallstop/96c5d3cd0d6045b0571de6448f052369 to your computer and use it in GitHub Desktop.
Save wallstop/96c5d3cd0d6045b0571de6448f052369 to your computer and use it in GitHub Desktop.
TimedCache
namespace Core.DataStructure
{
using System;
using Helper;
using Random;
using UnityEngine;
public sealed class TimedCache<T>
{
public T Value
{
get
{
if (!_lastRead.HasValue || UnityHelpers.HasEnoughTimePassed(_lastRead.Value, _cacheTtl))
{
_value = _valueProducer();
_lastRead = Time.time;
if (_useJitter)
{
_lastRead += SystemRandom.Instance.NextFloat(-0.1f, 0.1f);
}
}
return _value;
}
}
private readonly Func<T> _valueProducer;
private readonly float _cacheTtl;
private readonly bool _useJitter;
private float? _lastRead;
private T _value;
public TimedCache(Func<T> valueProducer, float cacheTtl, bool useJitter = false)
{
_valueProducer = valueProducer ?? throw new ArgumentNullException(nameof(valueProducer));
if (cacheTtl < 0)
{
throw new ArgumentException(nameof(cacheTtl));
}
_cacheTtl = cacheTtl;
_useJitter = useJitter;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment