Skip to content

Commit 95136a6

Browse files
committed
Use async iterators in Defer.
1 parent c80b4f1 commit 95136a6

File tree

1 file changed

+38
-0
lines changed
  • Ix.NET/Source/System.Interactive.Async/System/Linq/Operators

1 file changed

+38
-0
lines changed

Ix.NET/Source/System.Interactive.Async/System/Linq/Operators/Defer.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,39 @@ public static IAsyncEnumerable<TSource> Defer<TSource>(Func<IAsyncEnumerable<TSo
1616
if (factory == null)
1717
throw Error.ArgumentNull(nameof(factory));
1818

19+
#if USE_ASYNC_ITERATOR
20+
return Create(Core);
21+
22+
async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
23+
{
24+
await foreach (TSource item in factory().WithCancellation(cancellationToken).ConfigureAwait(false))
25+
{
26+
yield return item;
27+
}
28+
}
29+
#else
1930
return new DeferIterator<TSource>(factory);
31+
#endif
2032
}
2133

2234
public static IAsyncEnumerable<TSource> Defer<TSource>(Func<Task<IAsyncEnumerable<TSource>>> factory)
2335
{
2436
if (factory == null)
2537
throw Error.ArgumentNull(nameof(factory));
2638

39+
#if USE_ASYNC_ITERATOR
40+
return Create(Core);
41+
42+
async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
43+
{
44+
await foreach (TSource item in (await factory().ConfigureAwait(false)).WithCancellation(cancellationToken).ConfigureAwait(false))
45+
{
46+
yield return item;
47+
}
48+
}
49+
#else
2750
return new AsyncDeferIterator<TSource>(factory);
51+
#endif
2852
}
2953

3054
#if !NO_DEEP_CANCELLATION
@@ -33,10 +57,23 @@ public static IAsyncEnumerable<TSource> Defer<TSource>(Func<CancellationToken, T
3357
if (factory == null)
3458
throw Error.ArgumentNull(nameof(factory));
3559

60+
#if USE_ASYNC_ITERATOR
61+
return Create(Core);
62+
63+
async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
64+
{
65+
await foreach (TSource item in (await factory(cancellationToken).ConfigureAwait(false)).WithCancellation(cancellationToken).ConfigureAwait(false))
66+
{
67+
yield return item;
68+
}
69+
}
70+
#else
3671
return new AsyncDeferIteratorWithCancellation<TSource>(factory);
72+
#endif
3773
}
3874
#endif
3975

76+
#if !USE_ASYNC_ITERATOR
4077
private sealed class DeferIterator<T> : AsyncIteratorBase<T>
4178
{
4279
private readonly Func<IAsyncEnumerable<T>> _factory;
@@ -209,4 +246,5 @@ private async ValueTask<bool> InitializeAndMoveNextAsync()
209246
}
210247
#endif
211248
}
249+
#endif
212250
}

0 commit comments

Comments
 (0)