DatabaseAsync.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using UnityEngine;
  2. using XGame.Framework.Asset;
  3. using XGame.Framework.Asyncs;
  4. using XGame.Framework.Serialization;
  5. namespace XGame.Framework.Database
  6. {
  7. public class DatabaseAsync<TTable> : Async, IDatabaseAsync<TTable> where TTable : class, ITable
  8. {
  9. public string TableName { get; private set; }
  10. //private string _text;
  11. private IAssetLoadAsync<TextAsset> _loadAsync;
  12. private byte[] _bytes;
  13. public DatabaseAsync(string tableName)
  14. {
  15. TableName = tableName;
  16. }
  17. public TRepository GetResult<TRepository>() where TRepository : TableRepository<TTable, TRepository>
  18. {
  19. if (_bytes == null || _bytes.Length == 0)
  20. {
  21. return default;
  22. }
  23. return SerializationUtils.Read<TRepository>(_bytes);
  24. //if (string.IsNullOrEmpty(_text))
  25. //{
  26. // return default(T[]);
  27. //}
  28. //return XJson.ToObject<T[]>(_text);
  29. }
  30. protected override void OnRemoveAll()
  31. {
  32. _loadAsync?.RemoveOn(OnLoaded);
  33. _loadAsync = null;
  34. _bytes = null;
  35. }
  36. public void Start()
  37. {
  38. _loadAsync = AssetManager.LoadAsync<TextAsset>(TableName);
  39. _loadAsync.On(OnLoaded);
  40. //try
  41. //{
  42. // var uri = FileUtils.GetFileUrl($"Tables/{TableName}.json");
  43. // var request = UnityWebRequest.Get(uri);
  44. // var operation = request.SendWebRequest();
  45. // operation.completed += (op) =>
  46. // {
  47. // if (request.result == UnityWebRequest.Result.Success)
  48. // {
  49. // _text = request.downloadHandler.text;
  50. // }
  51. // else
  52. // {
  53. // _text = string.Empty;
  54. // State = request.error;
  55. // Log.Error($"DatabaseAsync failed. URL:{uri} Result:{request.result} Error:{request.error}");
  56. // }
  57. // Completed();
  58. // };
  59. //}
  60. //catch (Exception ex)
  61. //{
  62. // Log.Exception($"DatabaseAsync Name:{TableName}", ex);
  63. //}
  64. }
  65. private void OnLoaded(IAsync _)
  66. {
  67. var loadAsync = _loadAsync;
  68. _loadAsync = null;
  69. var result = loadAsync.Result;
  70. _bytes = result?.bytes ?? null;
  71. State = loadAsync.State;
  72. Completed();
  73. AssetManager.Recycle(result);
  74. }
  75. }
  76. }