70 lines
2.6 KiB
C#
70 lines
2.6 KiB
C#
#nullable enable
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using Cysharp.Threading.Tasks;
|
||
using ShrinkApp;
|
||
using ShrinkContext;
|
||
using ShrinkDataSaver;
|
||
|
||
namespace ShrinkDataSaver.Integration.App
|
||
{
|
||
/// <summary>
|
||
/// ShrinkDataSaver 的原生 Cordis 组件(阶段 3):
|
||
/// - 提供 <c>shrink.service.datasaver</c> 余效应键(门面服务);
|
||
/// - 初始化为前向;停用时的终止动作为最终落盘设置(补偿式收尾:
|
||
/// 存档写入本身跨会话持久,不可严格求逆,以 flush 保证一致性,见论文 6.1 扣留与补偿);
|
||
/// - 与经典 ShrinkDataSaverAppInstaller(ModuleId "shrink.datasaver")二选一使用。
|
||
/// </summary>
|
||
public sealed class ShrinkDataSaverAppComponent : IShrinkComponent
|
||
{
|
||
public const string ServiceKey = "shrink.service.datasaver";
|
||
public const string ModuleKey = "app.module.shrink.datasaver";
|
||
|
||
private static readonly string[] ProvideKeys = { ModuleKey, ServiceKey };
|
||
|
||
public string Name => "shrink.datasaver";
|
||
|
||
public IReadOnlyList<string> Inject => Array.Empty<string>();
|
||
|
||
public IReadOnlyList<string> Provide => ProvideKeys;
|
||
|
||
public async UniTask ApplyAsync(ShrinkCtx ctx, object? config)
|
||
{
|
||
// 编辑器/EditMode 环境下 DontDestroyOnLoad 会抛异常,驱动只在播放模式常驻
|
||
ShrinkDataSaverRuntime.Initialize(new ShrinkDataSaverRuntimeConfig
|
||
{
|
||
#if UNITY_5_3_OR_NEWER
|
||
DontDestroyOnLoadDriver = UnityEngine.Application.isPlaying
|
||
#else
|
||
DontDestroyOnLoadDriver = false
|
||
#endif
|
||
});
|
||
var facade = new ShrinkDataSaverService();
|
||
ctx.Set(ServiceKey, facade, new ShrinkDataSaverAccessPolicy(facade));
|
||
ctx.Set(ModuleKey, Name);
|
||
|
||
if (config is ShrinkAppServices appServices)
|
||
{
|
||
appServices.Register(facade);
|
||
ctx.EffectInverse(() =>
|
||
{
|
||
appServices.TryUnregister(facade);
|
||
return UniTask.CompletedTask;
|
||
});
|
||
}
|
||
|
||
await ctx.EffectAsync(async () =>
|
||
{
|
||
await UniTask.CompletedTask;
|
||
return () =>
|
||
{
|
||
// 终止动作(触发式):停用时把防抖中的设置写盘。
|
||
// 磁盘 IO 在线程池完成,不阻塞停用链;未初始化环境安全跳过(SaveAsync 守卫)。
|
||
ShrinkSettings.SaveAsync().Forget();
|
||
return UniTask.CompletedTask;
|
||
};
|
||
});
|
||
}
|
||
}
|
||
}
|