UniTask/Assets/UniRx.Async/Triggers/AsyncDestroyTrigger.cs

98 lines
2.6 KiB
C#
Raw Normal View History

2019-05-19 23:14:47 +08:00
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Threading;
using UnityEngine;
namespace UniRx.Async.Triggers
{
public static partial class AsyncTriggerExtensions
{
public static AsyncDestroyTrigger GetAsyncDestroyTrigger(this GameObject gameObject)
{
return GetOrAddComponent<AsyncDestroyTrigger>(gameObject);
}
public static AsyncDestroyTrigger GetAsyncDestroyTrigger(this Component component)
{
return component.gameObject.GetAsyncDestroyTrigger();
}
}
2019-05-19 23:14:47 +08:00
[DisallowMultipleComponent]
public class AsyncDestroyTrigger : MonoBehaviour
{
bool awakeCalled = false;
2019-05-19 23:14:47 +08:00
bool called = false;
TriggerEvent<AsyncUnit> triggerEvent;
CancellationTokenSource cancellationTokenSource;
2019-05-19 23:14:47 +08:00
public CancellationToken CancellationToken
{
get
{
if (cancellationTokenSource == null)
{
cancellationTokenSource = new CancellationTokenSource();
}
return cancellationTokenSource.Token;
}
}
void Awake()
{
awakeCalled = true;
}
2019-05-19 23:14:47 +08:00
void OnDestroy()
{
called = true;
triggerEvent?.TrySetResult(AsyncUnit.Default);
2019-05-19 23:14:47 +08:00
cancellationTokenSource?.Cancel();
cancellationTokenSource?.Dispose();
triggerEvent = null;
2019-05-19 23:14:47 +08:00
}
public UniTask OnDestroyAsync()
{
if (called) return UniTask.CompletedTask;
if (!awakeCalled)
2019-05-19 23:14:47 +08:00
{
PlayerLoopHelper.AddAction(PlayerLoopTiming.Update, new AwakeMonitor(this));
2019-05-19 23:14:47 +08:00
}
if (triggerEvent == null)
2019-05-19 23:14:47 +08:00
{
triggerEvent = new TriggerEvent<AsyncUnit>();
2019-05-19 23:14:47 +08:00
}
return ((IAsyncOneShotTrigger)new AsyncTriggerHandler<AsyncUnit>(triggerEvent, true)).OneShotAsync();
}
class AwakeMonitor : IPlayerLoopItem
{
readonly AsyncDestroyTrigger trigger;
public AwakeMonitor(AsyncDestroyTrigger trigger)
2019-05-19 23:14:47 +08:00
{
this.trigger = trigger;
2019-05-19 23:14:47 +08:00
}
public bool MoveNext()
2019-05-19 23:14:47 +08:00
{
if (trigger.called) return false;
if (trigger == null)
{
trigger.OnDestroy();
return false;
}
return true;
2019-05-19 23:14:47 +08:00
}
}
}
}
#endif