forked from CommunityToolkit/WindowsCommunityToolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIncrementalLoadingCollection.cs
More file actions
309 lines (274 loc) · 11 KB
/
IncrementalLoadingCollection.cs
File metadata and controls
309 lines (274 loc) · 11 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Toolkit.Collections;
using Windows.Foundation;
using Windows.UI.Xaml.Data;
namespace Microsoft.Toolkit.Uwp
{
/// <summary>
/// This class represents an <see cref="ObservableCollection{IType}"/> whose items can be loaded incrementally.
/// </summary>
/// <typeparam name="TSource">
/// The data source that must be loaded incrementally.
/// </typeparam>
/// <typeparam name="IType">
/// The type of collection items.
/// </typeparam>
/// <seealso cref="IIncrementalSource{TSource}"/>
/// <seealso cref="ISupportIncrementalLoading"/>
public class IncrementalLoadingCollection<TSource, IType> : ObservableCollection<IType>,
ISupportIncrementalLoading
where TSource : IIncrementalSource<IType>
{
private readonly SemaphoreSlim _mutex = new SemaphoreSlim(1);
/// <summary>
/// Gets or sets an <see cref="Action"/> that is called when a retrieval operation begins.
/// </summary>
public Action OnStartLoading { get; set; }
/// <summary>
/// Gets or sets an <see cref="Action"/> that is called when a retrieval operation ends.
/// </summary>
public Action OnEndLoading { get; set; }
/// <summary>
/// Gets or sets an <see cref="Action"/> that is called if an error occurs during data retrieval. The actual <see cref="Exception"/> is passed as an argument.
/// </summary>
public Action<Exception> OnError { get; set; }
/// <summary>
/// Gets a value indicating the source of incremental loading.
/// </summary>
protected TSource Source { get; }
/// <summary>
/// Gets a value indicating how many items that must be retrieved for each incremental call.
/// </summary>
protected int ItemsPerPage { get; }
/// <summary>
/// Gets or sets a value indicating The zero-based index of the current items page.
/// </summary>
protected int CurrentPageIndex { get; set; }
private bool _isLoading;
private bool _hasMoreItems;
private CancellationToken _cancellationToken;
private bool _refreshOnLoad;
/// <summary>
/// Gets a value indicating whether new items are being loaded.
/// </summary>
public bool IsLoading
{
get
{
return _isLoading;
}
private set
{
if (value != _isLoading)
{
_isLoading = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsLoading)));
if (_isLoading)
{
OnStartLoading?.Invoke();
}
else
{
OnEndLoading?.Invoke();
}
}
}
}
/// <summary>
/// Gets a value indicating whether the collection contains more items to retrieve.
/// </summary>
public bool HasMoreItems
{
get
{
if (_cancellationToken.IsCancellationRequested)
{
return false;
}
return _hasMoreItems;
}
private set
{
if (value != _hasMoreItems)
{
_hasMoreItems = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(HasMoreItems)));
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="IncrementalLoadingCollection{TSource, IType}"/> class optionally specifying how many items to load for each data page.
/// </summary>
/// <param name="itemsPerPage">
/// The number of items to retrieve for each call. Default is 20.
/// </param>
/// <param name="onStartLoading">
/// An <see cref="Action"/> that is called when a retrieval operation begins.
/// </param>
/// <param name="onEndLoading">
/// An <see cref="Action"/> that is called when a retrieval operation ends.
/// </param>
/// <param name="onError">
/// An <see cref="Action"/> that is called if an error occurs during data retrieval.
/// </param>
/// <seealso cref="IIncrementalSource{TSource}"/>
public IncrementalLoadingCollection(int itemsPerPage = 20, Action onStartLoading = null, Action onEndLoading = null, Action<Exception> onError = null)
: this(Activator.CreateInstance<TSource>(), itemsPerPage, onStartLoading, onEndLoading, onError)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IncrementalLoadingCollection{TSource, IType}"/> class using the specified <see cref="IIncrementalSource{TSource}"/> implementation and, optionally, how many items to load for each data page.
/// </summary>
/// <param name="source">
/// An implementation of the <see cref="IIncrementalSource{TSource}"/> interface that contains the logic to actually load data incrementally.
/// </param>
/// <param name="itemsPerPage">
/// The number of items to retrieve for each call. Default is 20.
/// </param>
/// <param name="onStartLoading">
/// An <see cref="Action"/> that is called when a retrieval operation begins.
/// </param>
/// <param name="onEndLoading">
/// An <see cref="Action"/> that is called when a retrieval operation ends.
/// </param>
/// <param name="onError">
/// An <see cref="Action"/> that is called if an error occurs during data retrieval.
/// </param>
/// <seealso cref="IIncrementalSource{TSource}"/>
public IncrementalLoadingCollection(TSource source, int itemsPerPage = 20, Action onStartLoading = null, Action onEndLoading = null, Action<Exception> onError = null)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
Source = source;
OnStartLoading = onStartLoading;
OnEndLoading = onEndLoading;
OnError = onError;
ItemsPerPage = itemsPerPage;
_hasMoreItems = true;
}
/// <summary>
/// Initializes incremental loading from the view.
/// </summary>
/// <param name="count">
/// The number of items to load.
/// </param>
/// <returns>
/// An object of the <see cref="LoadMoreItemsAsync(uint)"/> that specifies how many items have been actually retrieved.
/// </returns>
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
=> LoadMoreItemsAsync(count, new CancellationToken(false)).AsAsyncOperation();
/// <summary>
/// Clears the collection and triggers/forces a reload of the first page
/// </summary>
/// <returns>This method does not return a result</returns>
public Task RefreshAsync()
{
if (IsLoading)
{
_refreshOnLoad = true;
}
else
{
var previousCount = Count;
Clear();
CurrentPageIndex = 0;
HasMoreItems = true;
if (previousCount == 0)
{
// When the list was empty before clearing, the automatic reload isn't fired, so force a reload.
return LoadMoreItemsAsync(0).AsTask();
}
}
return Task.CompletedTask;
}
/// <summary>
/// Actually performs the incremental loading.
/// </summary>
/// <param name="cancellationToken">
/// Used to propagate notification that operation should be canceled.
/// </param>
/// <returns>
/// Returns a collection of <typeparamref name="IType"/>.
/// </returns>
protected virtual async Task<IEnumerable<IType>> LoadDataAsync(CancellationToken cancellationToken)
{
var result = await Source.GetPagedItemsAsync(CurrentPageIndex, ItemsPerPage, cancellationToken)
.ContinueWith(
t =>
{
if (t.IsFaulted)
{
throw t.Exception;
}
if (t.IsCompletedSuccessfully)
{
CurrentPageIndex += 1;
}
return t.Result;
}, cancellationToken);
return result;
}
private async Task<LoadMoreItemsResult> LoadMoreItemsAsync(uint count, CancellationToken cancellationToken)
{
uint resultCount = 0;
_cancellationToken = cancellationToken;
// TODO (2021.05.05): Make use common AsyncMutex class.
// AsyncMutex is located at Microsoft.Toolkit.Uwp.UI.Media/Extensions/System.Threading.Tasks/AsyncMutex.cs at the time of this note.
await _mutex.WaitAsync();
try
{
if (!_cancellationToken.IsCancellationRequested)
{
IEnumerable<IType> data = null;
try
{
IsLoading = true;
data = await LoadDataAsync(_cancellationToken);
}
catch (OperationCanceledException)
{
// The operation has been canceled using the Cancellation Token.
}
catch (Exception ex) when (OnError != null)
{
OnError.Invoke(ex);
}
if (data != null && data.Any() && !_cancellationToken.IsCancellationRequested)
{
resultCount = (uint)data.Count();
foreach (var item in data)
{
Add(item);
}
}
else
{
HasMoreItems = false;
}
}
}
finally
{
IsLoading = false;
if (_refreshOnLoad)
{
_refreshOnLoad = false;
await RefreshAsync();
}
_mutex.Release();
}
return new LoadMoreItemsResult { Count = resultCount };
}
}
}