카테고리 없음

[Unity] Simple async EventHandler in Unity using Cysharp/UniTask

성엽이 2023. 5. 17. 15:18

https://gist.github.com/JanikHelbig/8228e3fc6e118757faa8a61c3d8370af

 

Simple async EventHandler in Unity using Cysharp/UniTask

Simple async EventHandler in Unity using Cysharp/UniTask - EventHandlerAsync.cs

gist.github.com

 

EventHandler 에 등록된 함수'들'의 Invoke 후에 작업이 모두 완료되기까지 기다리게하는 유틸

 

UniTask 사용.

 

 

EventHandlerAsyncExtensions.cs


using Cysharp.Threading.Tasks;
using System;

public delegate UniTask EventHandlerAsync(object sender, EventArgs e);

public static class EventHandlerAsyncExtensions {
    public static UniTask InvokeAsync(this EventHandlerAsync handler, object sender, EventArgs e) {
        Delegate[] delegates = handler?.GetInvocationList();

        if (delegates == null || delegates.Length == 0)
            return UniTask.CompletedTask;

        var tasks = new UniTask[delegates.Length];

        for (var i = 0; i < delegates.Length; i++) {
            tasks[i] = (UniTask)delegates[i].DynamicInvoke(sender, e);
        }

        return UniTask.WhenAll(tasks);
    }
}

 

 

ExampleInvokeAsync.cs


    public static event EventHandlerAsync OnChangedAsync;

	private void Start(){
    	StartCoroutine(UpdateAll());
	}
    
	private IEnumerator UpdateAll() {
        yield return UpdateAllInvokeAsync();
    }

    private async UniTaskVoid UpdateAllInvokeAsync() {
        await OnChangedAsync.InvokeAsync(this, EventArgs.Empty);        
    }

 

ExampleOnChanged.cs


    private void OnEnable() {        
        ExampleInvokeAsync.OnChangedAsync += Example_OnChangedInvokeAsync;                
    }

    private void OnDisable() {        
        ExampleInvokeAsync.OnChangedAsync -= Example_OnChangedInvokeAsync;                
    }

    private UniTask Example_OnChangedInvokeAsync(object sender, EventArgs e) {        
        // Do Something works..
        UpdateAnything();        
        return UniTask.CompletedTask;
    }