-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncSample.cs
60 lines (55 loc) · 2.15 KB
/
AsyncSample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Collections.Generic;
using System.Threading.Tasks;
using LazySequence;
namespace Samples
{
/// <summary>
/// Examples of using AsyncLazySequence
/// </summary>
public class AsyncSample
{
/// <summary>
/// Create a sequence to paginate server requests
/// </summary>
/// <returns></returns>
public static async Task Pagination()
{
/*
* An AsyncLazySequence can be used as a medium to lazily paginate
* over web requests to your API.
*/
var pageSize = 10;
IAsyncEnumerable<object?> paginatedServerRequestCreator = AsyncLazySequence<object?, int>.Create(
firstElement: null,
initialState: 0,
async (prev, currentOffset, index) =>
{
var serverResponse = await ServerPageRequest(currentOffset, pageSize);
return (
nextElement: serverResponse,
iterationState: currentOffset + pageSize,
isLastElement: false);
});
// One way is to use the AsyncEnumerator as state and occasionally get the next
// paged response
IAsyncEnumerator<object?> paginatedServerRequests = paginatedServerRequestCreator.GetAsyncEnumerator();
(var hasElement, var pagedResponse1) = await paginatedServerRequests.TryGetNextAsync();
// The other way is to use the fact that it can be iterated on in a foreach loop
await foreach (var pagedResponse2 in paginatedServerRequestCreator)
{
// use pagedResponse2 here
}
}
/// <summary>
/// Mock server page request that takes a startIndex and pageSize
/// </summary>
/// <param name="startIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
private static async Task<object> ServerPageRequest(int startIndex, int pageSize)
{
await Task.Delay(100);
return Task.FromResult(new object());
}
}
}