Skip to content

Instantly share code, notes, and snippets.

@kyubuns
Last active May 17, 2020 07:57
Show Gist options
  • Save kyubuns/68a49fabdf4dfcaf66a0874bfbff82d0 to your computer and use it in GitHub Desktop.
Save kyubuns/68a49fabdf4dfcaf66a0874bfbff82d0 to your computer and use it in GitHub Desktop.
var hoge = new[] { 1, 2, 3 };
hoge.ToUniTaskAsyncEnumerable().ForEachAwaitAsync(async x =>
{
Debug.Log($"Start hoge = {x}");
await UniTask.Delay(TimeSpan.FromSeconds(1));
Debug.Log($"Finish hoge = {x}");
}).Forget();
// Output
/*
0.0 | Start hoge = 1
1.0 | Finish hoge = 1
1.0 | Start hoge = 2
2.0 | Finish hoge = 2
2.0 | Start hoge = 3
3.0 | Finish hoge = 3
*/
var hp = new AsyncReactiveProperty<int>(10);
Debug.Log("Set hp = 10");
hp.ForEachAwaitAsync(async x =>
{
Debug.Log($"Start hp = {x}");
await UniTask.Delay(TimeSpan.FromSeconds(1));
Debug.Log($"Finish hp = {x}");
}).Forget();
await UniTask.Delay(TimeSpan.FromSeconds(0.3));
Debug.Log("Set hp = 20");
hp.Value = 20;
await UniTask.Delay(TimeSpan.FromSeconds(0.8));
Debug.Log("Set hp = 30");
hp.Value = 30;
// Output
/*
0.0 | Set hp = 10
0.3 | Set hp = 20
0.3 | Start hp = 20
1.1 | Set hp = 30
1.3 | Finish hp = 20
*/
// 想像していた挙動1 / 全部流れてくる
/*
0.0 | Set hp = 10
0.0 | Start hp = 10
0.3 | Set hp = 20
1.0 | Finish hp = 10
1.0 | Start hp = 20
1.1 | Set hp = 30
2.0 | Finish hp = 20
2.0 | Start hp = 30
3.0 | Finish hp = 30
*/
// 想像していた挙動2 / ForEachAwaitAsync中のものは流れてこないが、最初の値は流れてくる
/*
0.0 | Set hp = 10
0.0 | Start hp = 10
0.3 | Set hp = 20
1.0 | Finish hp = 10
1.1 | Set hp = 30
1.1 | Start hp = 30
2.1 | Finish hp = 30
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment