1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using UnityEngine;
- using XGame.Framework.Asset;
- using XGame.Framework.Asyncs;
- using XGame.Framework.Serialization;
- namespace XGame.Framework.Database
- {
- public class DatabaseAsync<TTable> : Async, IDatabaseAsync<TTable> where TTable : class, ITable
- {
- public string TableName { get; private set; }
- //private string _text;
- private IAssetLoadAsync<TextAsset> _loadAsync;
- private byte[] _bytes;
- public DatabaseAsync(string tableName)
- {
- TableName = tableName;
- }
- public TRepository GetResult<TRepository>() where TRepository : TableRepository<TTable, TRepository>
- {
- if (_bytes == null || _bytes.Length == 0)
- {
- return default;
- }
- return SerializationUtils.Read<TRepository>(_bytes);
- //if (string.IsNullOrEmpty(_text))
- //{
- // return default(T[]);
- //}
- //return XJson.ToObject<T[]>(_text);
- }
- protected override void OnRemoveAll()
- {
- _loadAsync?.RemoveOn(OnLoaded);
- _loadAsync = null;
- _bytes = null;
- }
- public void Start()
- {
- _loadAsync = AssetManager.LoadAsync<TextAsset>(TableName);
- _loadAsync.On(OnLoaded);
- //try
- //{
- // var uri = FileUtils.GetFileUrl($"Tables/{TableName}.json");
- // var request = UnityWebRequest.Get(uri);
- // var operation = request.SendWebRequest();
- // operation.completed += (op) =>
- // {
- // if (request.result == UnityWebRequest.Result.Success)
- // {
- // _text = request.downloadHandler.text;
- // }
- // else
- // {
- // _text = string.Empty;
- // State = request.error;
- // Log.Error($"DatabaseAsync failed. URL:{uri} Result:{request.result} Error:{request.error}");
- // }
- // Completed();
- // };
- //}
- //catch (Exception ex)
- //{
- // Log.Exception($"DatabaseAsync Name:{TableName}", ex);
- //}
- }
- private void OnLoaded(IAsync _)
- {
- var loadAsync = _loadAsync;
- _loadAsync = null;
- var result = loadAsync.GetResult();
- _bytes = result?.bytes ?? null;
- State = loadAsync.State;
- Completed();
- AssetManager.Recycle(result);
- }
- }
- }
|