ソースコード
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace Kogane
{
<summary>
</summary>
public static class AsyncMessageBroker
{
private static Dictionary<Type, object> m_callbacksTable = new();
#if UNITY_EDITOR
<summary>
</summary>
[UnityEditor.InitializeOnEnterPlayMode]
private static void InitializeOnEnterPlayMode()
{
m_callbacksTable = new();
}
#endif
<summary>
</summary>
public static void Add<T>( Func<T, UniTask> callback )
{
var type = typeof( T );
if ( !m_callbacksTable.ContainsKey( type ) )
{
m_callbacksTable[ type ] = new List<Func<T, UniTask>>();
}
var callbacks = ( List<Func<T, UniTask>> )m_callbacksTable[ type ];
callbacks.Add( callback );
}
<summary>
</summary>
public static void Remove<T>( Func<T, UniTask> callback )
{
var type = typeof( T );
if ( !m_callbacksTable.ContainsKey( type ) ) return;
if ( m_callbacksTable[ type ] == null ) return;
var callbacks = ( List<Func<T, UniTask>> )m_callbacksTable[ type ];
callbacks.Remove( callback );
}
<summary>
</summary>
public static async UniTask SendAsync<T>( T data )
{
var type = typeof( T );
if ( !m_callbacksTable.TryGetValue( type, out var value ) ) return;
var callbacks = ( List<Func<T, UniTask>> )value;
if ( callbacks is not { Count: > 0 } ) return;
await UniTask.WhenAll( callbacks.Select( x => x( data ) ) );
}
}
}