Expand.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> Expand<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TSource>> selector)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. if (selector == null)
  18. throw new ArgumentNullException(nameof(selector));
  19. return CreateEnumerable(
  20. () =>
  21. {
  22. var e = default(IAsyncEnumerator<TSource>);
  23. var cts = new CancellationTokenDisposable();
  24. var a = new AssignableDisposable();
  25. var d = Disposable.Create(cts, a);
  26. var queue = new Queue<IAsyncEnumerable<TSource>>();
  27. queue.Enqueue(source);
  28. var current = default(TSource);
  29. var f = default(Func<CancellationToken, Task<bool>>);
  30. f = async ct =>
  31. {
  32. if (e == null)
  33. {
  34. if (queue.Count > 0)
  35. {
  36. var src = queue.Dequeue();
  37. e = src.GetEnumerator();
  38. a.Disposable = e;
  39. return await f(ct)
  40. .ConfigureAwait(false);
  41. }
  42. return false;
  43. }
  44. if (await e.MoveNext(ct)
  45. .ConfigureAwait(false))
  46. {
  47. var item = e.Current;
  48. var next = selector(item);
  49. queue.Enqueue(next);
  50. current = item;
  51. return true;
  52. }
  53. e = null;
  54. return await f(ct)
  55. .ConfigureAwait(false);
  56. };
  57. return CreateEnumerator(
  58. f,
  59. () => current,
  60. d.Dispose,
  61. e
  62. );
  63. });
  64. }
  65. }
  66. }