using System;
using System.Collections;
using System.Collections.Generic;
using UniRx.Triggers;
using UnityEngine;
namespace UniRx
{
public static partial class DisposableExtensions
{
/// Dispose self on target gameObject has been destroyed. Return value is self disposable.
public static T AddTo(this T disposable, GameObject gameObject)
where T : IDisposable
{
if (gameObject == null)
{
disposable.Dispose();
return disposable;
}
var trigger = gameObject.GetComponent();
if (trigger == null)
{
trigger = gameObject.AddComponent();
}
#pragma warning disable 618
// If gameObject is deactive, does not raise OnDestroy, watch and invoke trigger.
if (!trigger.IsActivated && !trigger.IsMonitoredActivate && !trigger.gameObject.activeInHierarchy)
{
trigger.IsMonitoredActivate = true;
MainThreadDispatcher.StartEndOfFrameMicroCoroutine(MonitorTriggerHealth(trigger, gameObject));
}
#pragma warning restore 618
trigger.AddDisposableOnDestroy(disposable);
return disposable;
}
static IEnumerator MonitorTriggerHealth(ObservableDestroyTrigger trigger, GameObject targetGameObject)
{
while (true)
{
yield return null;
if (trigger.IsActivated) yield break;
if (targetGameObject == null) // isDestroy
{
trigger.ForceRaiseOnDestroy(); // Force publish OnDestroy
yield break;
}
}
}
/// Dispose self on target gameObject has been destroyed. Return value is self disposable.
public static T AddTo(this T disposable, Component gameObjectComponent)
where T : IDisposable
{
if (gameObjectComponent == null)
{
disposable.Dispose();
return disposable;
}
return AddTo(disposable, gameObjectComponent.gameObject);
}
///
/// Add disposable(self) to CompositeDisposable(or other ICollection) and Dispose self on target gameObject has been destroyed.
/// Return value is self disposable.
///
public static T AddTo(this T disposable, ICollection container, GameObject gameObject)
where T : IDisposable
{
return disposable.AddTo(container).AddTo(gameObject);
}
///
/// Add disposable(self) to CompositeDisposable(or other ICollection) and Dispose self on target gameObject has been destroyed.
/// Return value is self disposable.
///
public static T AddTo(this T disposable, ICollection container, Component gameObjectComponent)
where T : IDisposable
{
return disposable.AddTo(container).AddTo(gameObjectComponent);
}
}
}