Last active
December 2, 2021 23:22
-
-
Save neuecc/006bfde5f8b3fe0def7a929b955f5fa2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// extension awaiter/methods can be used by this namespace | |
using UniRx.Async; | |
// You can return type as struct UniTask<T>, it is unity specialized lightweight alternative of Task<T> | |
// no(or less) allocation and fast excution for zero overhead async/await integrate with Unity | |
async UniTask<string> DemoAsync() | |
{ | |
// You can await Unity's AsyncObject | |
var asset = await Resources.LoadAsync<TextAsset>("foo"); | |
// .ConfigureAwait accepts progress callback | |
await SceneManager.LoadSceneAsync("scene2").ConfigureAwait(new Progress<float>(x => Debug.Log(x))); | |
// await frame-based operation(you can also await frame count by DelayFrame) | |
await UniTask.Delay(TimeSpan.FromSeconds(3)); | |
// like 'yield return WaitForEndOfFrame', or Rx's ObserveOn(scheduler) | |
await UniTask.Yield(PlayerLoopTiming.PostLateUpdate); | |
// You can await standard task | |
await Task.Run(() => 100); | |
// You can await IEnumerator coroutine | |
await ToaruCoroutineEnumerator(); | |
// get async webrequest | |
async UniTask<string> GetTextAsync(UnityWebRequest req) | |
{ | |
var op = await req.SendWebRequest(); | |
return op.downloadHandler.text; | |
} | |
var task1 = GetTextAsync(UnityWebRequest.Get("http://google.com")); | |
var task2 = GetTextAsync(UnityWebRequest.Get("http://bing.com")); | |
var task3 = GetTextAsync(UnityWebRequest.Get("http://yahoo.com")); | |
// concurrent async-wait and get result easily by tuple syntax | |
var (google, bing, yahoo) = await UniTask.WhenAll(task1, task2, task3); | |
// You can handle timeout easily | |
await GetTextAsync(UnityWebRequest.Get("http://unity.com")).Timeout(TimeSpan.FromMilliseconds(300)); | |
// return async-value.(or you can use `UniTask`(no result), `UniTaskVoid`(fire and forget)). | |
return (asset as TextAsset)?.text ?? throw new InvalidOperationException("Asset not found"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment