CachingGetter.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (c) 2024 Vuplex Inc. All rights reserved.
  2. //
  3. // Licensed under the Vuplex Commercial Software Library License, you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // https://vuplex.com/commercial-library-license
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. using System;
  15. using System.Collections;
  16. using UnityEngine;
  17. namespace Vuplex.WebView.Internal {
  18. /// <summary>
  19. /// Internal utility class to help cache values that may change but
  20. /// shouldn't be looked up every frame.
  21. /// </summary>
  22. class CachingGetter<TResult> {
  23. public CachingGetter(Func<TResult> getterFunction, int cacheInvalidationPeriodSeconds, MonoBehaviour monoBehaviourForCoroutine) {
  24. _getterFunction = getterFunction;
  25. _waitForSeconds = new WaitForSeconds(cacheInvalidationPeriodSeconds);
  26. monoBehaviourForCoroutine.StartCoroutine(_invalidateCachePeriodically());
  27. }
  28. public TResult GetValue() {
  29. if (_valueNeedsToBeUpdated) {
  30. _cachedValue = _getterFunction();
  31. _valueNeedsToBeUpdated = false;
  32. }
  33. return _cachedValue;
  34. }
  35. Func<TResult> _getterFunction;
  36. bool _valueNeedsToBeUpdated = true;
  37. TResult _cachedValue;
  38. WaitForSeconds _waitForSeconds;
  39. IEnumerator _invalidateCachePeriodically() {
  40. while (true) {
  41. yield return _waitForSeconds;
  42. _valueNeedsToBeUpdated = true;
  43. }
  44. }
  45. }
  46. }