This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathSequentialListSource.cs
198 lines (168 loc) · 5.98 KB
/
SequentialListSource.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using GitHub.Logging;
using GitHub.Models;
using ReactiveUI;
using Serilog;
namespace GitHub.Collections
{
/// <summary>
/// An <see cref="IVirtualizingListSource{T}"/> that loads GraphQL pages sequentially, and
/// transforms items into a view model after reading.
/// </summary>
/// <typeparam name="TModel">The type of the model read from the remote data source.</typeparam>
/// <typeparam name="TViewModel">The type of the transformed view model.</typeparam>
/// <remarks>
/// GraphQL can only read pages of data sequentally, so in order to read item 450 (assuming a
/// page size of 100), the list source must read pages 1, 2, 3 and 4 in that order. Classes
/// deriving from this class only need to implement <see cref="LoadPage(string)"/> to load a
/// single page and this class will handle the rest.
///
/// In addition, items will usually need to be transformed into a view model after reading. The
/// implementing class overrides <see cref="CreateViewModel(TModel)"/> to carry out that
/// transformation.
/// </remarks>
public abstract class SequentialListSource<TModel, TViewModel> : ReactiveObject, IVirtualizingListSource<TViewModel>
{
static readonly ILogger log = LogManager.ForContext<SequentialListSource<TModel, TViewModel>>();
readonly Dispatcher dispatcher;
readonly object loadLock = new object();
Dictionary<int, Page<TModel>> pages = new Dictionary<int, Page<TModel>>();
Task loading = Task.CompletedTask;
bool disposed;
bool isLoading;
int? count;
int nextPage;
int loadTo;
string after;
/// <summary>
/// Initializes a new instance of the <see cref="SequentialListSource{TModel, TViewModel}"/> class.
/// </summary>
public SequentialListSource()
{
dispatcher = Application.Current?.Dispatcher;
}
/// <inheritdoc/>
public bool IsLoading
{
get { return isLoading; }
private set { this.RaiseAndSetIfChanged(ref isLoading, value); }
}
/// <inheritdoc/>
public virtual int PageSize => 100;
event EventHandler PageLoaded;
public void Dispose() => disposed = true;
/// <inheritdoc/>
public async Task<int> GetCount()
{
dispatcher?.VerifyAccess();
if (!count.HasValue)
{
count = (await EnsureLoaded(0).ConfigureAwait(false)).TotalCount;
}
return count.Value;
}
/// <inheritdoc/>
public async Task<IReadOnlyList<TViewModel>> GetPage(int pageNumber)
{
dispatcher?.VerifyAccess();
var page = await EnsureLoaded(pageNumber);
if (page == null)
{
return null;
}
var result = page.Items
.Select(CreateViewModel)
.ToList();
pages.Remove(pageNumber);
return result;
}
/// <summary>
/// When overridden in a derived class, transforms a model into a view model after loading.
/// </summary>
/// <param name="model">The model.</param>
/// <returns>The view model.</returns>
protected abstract TViewModel CreateViewModel(TModel model);
/// <summary>
/// When overridden in a derived class reads a page of results from GraphQL.
/// </summary>
/// <param name="after">The GraphQL after cursor.</param>
/// <returns>A task which returns the page of results.</returns>
protected abstract Task<Page<TModel>> LoadPage(string after);
/// <summary>
/// Called when the source begins loading pages.
/// </summary>
protected virtual void OnBeginLoading()
{
IsLoading = true;
}
/// <summary>
/// Called when the source finishes loading pages.
/// </summary>
protected virtual void OnEndLoading()
{
IsLoading = false;
}
async Task<Page<TModel>> EnsureLoaded(int pageNumber)
{
if (pageNumber < nextPage)
{
return pages[pageNumber];
}
var pageLoaded = WaitPageLoaded(pageNumber);
loadTo = Math.Max(loadTo, pageNumber);
while (!disposed)
{
lock (loadLock)
{
if (loading.IsCompleted)
{
loading = Load();
}
}
await Task.WhenAny(loading, pageLoaded).ConfigureAwait(false);
if (pageLoaded.IsCompleted)
{
return pages[pageNumber];
}
}
return null;
}
Task WaitPageLoaded(int page)
{
var tcs = new TaskCompletionSource<bool>();
EventHandler handler = null;
handler = (s, e) =>
{
if (nextPage > page)
{
tcs.SetResult(true);
PageLoaded -= handler;
}
};
PageLoaded += handler;
return tcs.Task;
}
async Task Load()
{
OnBeginLoading();
while (nextPage <= loadTo && !disposed)
{
await LoadNextPage().ConfigureAwait(false);
PageLoaded?.Invoke(this, EventArgs.Empty);
}
OnEndLoading();
}
async Task LoadNextPage()
{
log.Debug("Loading page {Number} of {ModelType}", nextPage, typeof(TModel));
var page = await LoadPage(after).ConfigureAwait(false);
pages[nextPage++] = page;
after = page.EndCursor;
}
}
}