Repository navigation
Expand file tree
/
Copy pathWhenAnyExamples.cs
More file actions
491 lines (391 loc) · 18.9 KB
/
Copy pathWhenAnyExamples.cs
File metadata and controls
491 lines (391 loc) · 18.9 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
// ReactiveUI and Contributors licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System.Globalization;
using ReactiveUI.Binding.Documentation.Banking;
using ReactiveUI.Binding.Documentation.GitHub;
using ReactiveUI.Binding.Documentation.Todo;
using ReactiveUI.Primitives;
using ReactiveUI.Primitives.Signals;
namespace ReactiveUI.Binding.Documentation.Observing;
/// <summary>
/// Shows every <c>WhenAny</c> overload, from one observed property to twelve. <c>WhenAny</c> hands the selector one
/// <see cref="IObservedChange{TSender, TValue}"/> per property instead of the bare value. The change names the object
/// you observed and the current value. The selector runs when you subscribe and again after each change.
/// </summary>
public static class WhenAnyExamples
{
/// <summary>The identifier of the registration task.</summary>
private const int RegistrationId = 7;
/// <summary>The title of the registration task.</summary>
private const string RegistrationTitle = "Renew car registration";
/// <summary>The title the registration task is renamed to.</summary>
private const string RenamedTitle = "Renew car registration online";
/// <summary>The notes of the registration task.</summary>
private const string RegistrationNotes = "Bring the insurance certificate";
/// <summary>The label of an errand.</summary>
private const string ErrandsTag = "errands";
/// <summary>The label of a car task.</summary>
private const string CarTag = "car";
/// <summary>The label of an urgent task.</summary>
private const string UrgentTag = "urgent";
/// <summary>The prefix of a finished checklist line.</summary>
private const string DoneMark = "[x] ";
/// <summary>The prefix of an open checklist line.</summary>
private const string OpenMark = "[ ] ";
/// <summary>The format of a deadline in a headline.</summary>
private const string IsoDay = "yyyy-MM-dd";
/// <summary>The identifier of the account the money leaves.</summary>
private const string EverydayId = "ACC-1001";
/// <summary>The name of the account the money leaves.</summary>
private const string EverydayName = "Everyday";
/// <summary>The currency of the account the money leaves.</summary>
private const string Currency = "AUD";
/// <summary>The balance of the account the money leaves.</summary>
private const decimal EverydayBalance = 4200.50M;
/// <summary>How far below zero the account may go.</summary>
private const decimal EverydayOverdraft = 500M;
/// <summary>The identifier of the payee.</summary>
private const int PayeeId = 3;
/// <summary>The name of the payee.</summary>
private const string PayeeName = "Harbour Realty";
/// <summary>The account that receives the money.</summary>
private const string PayeeAccountNumber = "062-000 1234 5678";
/// <summary>The most the customer allows in one transfer to the payee.</summary>
private const decimal PayeeLimit = 1000M;
/// <summary>The amount the customer starts with.</summary>
private const decimal RentAmount = 250M;
/// <summary>An amount above the payee's limit and above the available balance.</summary>
private const decimal AboveAvailable = 9000M;
/// <summary>An amount above the payee's limit and below the available balance.</summary>
private const decimal AbovePayeeLimit = 1500M;
/// <summary>The reference the customer starts with.</summary>
private const string RentReference = "Rent March";
/// <summary>The reference the customer changes to.</summary>
private const string RentReferenceRevised = "Rent March, paid early";
/// <summary>The number the user types first.</summary>
private const string FirstIssueNumber = "100";
/// <summary>The number the user types second.</summary>
private const string SecondIssueNumber = "101";
/// <summary>The number the user types last.</summary>
private const string ThirdIssueNumber = "102";
/// <summary>The value that stands for text that is not a number.</summary>
private const int NotANumber = -1;
/// <summary>The repository the issue numbers belong to.</summary>
private const string Webshop = "acme/webshop";
/// <summary>The deadline of the registration task.</summary>
private static readonly DateOnly _registrationDue = new(2026, 3, 20);
/// <summary>The deadline the registration task moves to.</summary>
private static readonly DateOnly _movedDue = new(2026, 3, 27);
/// <summary>The labels of the registration task.</summary>
private static readonly IReadOnlyList<string> _registrationTags = [ErrandsTag, CarTag];
/// <summary>The labels of the registration task once it is urgent.</summary>
private static readonly IReadOnlyList<string> _urgentTags = [ErrandsTag, CarTag, UrgentTag];
/// <summary>The payee of the transfer.</summary>
private static readonly Payee _landlord = new(PayeeId, PayeeName, PayeeAccountNumber, PayeeLimit);
/// <summary>Observes the title of a to-do item and prints each change as it arrives.</summary>
public static void ObserveTodoTitleChange()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item.WhenAny(static x => x.Title, static change => change).Subscribe(static change => Console.WriteLine(change.Value));
item.Title = RenamedTitle;
// Output:
// Renew car registration
// Renew car registration online
}
/// <summary>Turns the title of a to-do item into its length, as a character counter does.</summary>
public static void ProjectTodoTitleLength()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item.WhenAny(static x => x.Title, static title => title.Value.Length).Subscribe(Console.WriteLine);
item.Title = RenamedTitle;
// Output:
// 22
// 29
}
/// <summary>Turns the title and the done flag into one checklist line.</summary>
public static void ProjectTodoChecklistLine()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item
.WhenAny(static x => x.Title, static x => x.IsDone, static (title, isDone) => (isDone.Value ? DoneMark : OpenMark) + title.Value)
.Subscribe(Console.WriteLine);
item.IsDone = true;
// Output:
// [ ] Renew car registration
// [x] Renew car registration
}
/// <summary>Works out how urgent a to-do item is from three properties; a finished item is never urgent.</summary>
public static void ProjectTodoEffectivePriority()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item
.WhenAny(static x => x.Title, static x => x.IsDone, static x => x.Priority, static (_, isDone, priority) => isDone.Value ? TodoPriority.Low : priority.Value)
.Subscribe(static priority => Console.WriteLine(priority));
item.Priority = TodoPriority.High;
item.IsDone = true;
// Output:
// Normal
// High
// Low
}
/// <summary>Builds a headline with the deadline from four properties.</summary>
public static void ProjectTodoHeadline()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item
.WhenAny(
static x => x.Title,
static x => x.Notes,
static x => x.IsDone,
static x => x.DueDate,
static (title, _, isDone, due) =>
due.Value is { } day && !isDone.Value ? $"{title.Value} due {day.ToString(IsoDay, CultureInfo.InvariantCulture)}" : title.Value)
.Subscribe(Console.WriteLine);
item.DueDate = _movedDue;
// Output:
// Renew car registration due 2026-03-20
// Renew car registration due 2026-03-27
}
/// <summary>Decides from five properties whether a to-do item needs attention now.</summary>
public static void ProjectTodoNeedsAttention()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item
.WhenAny(
static x => x.Title,
static x => x.Notes,
static x => x.IsDone,
static x => x.DueDate,
static x => x.Priority,
static (_, _, isDone, due, priority) => !isDone.Value && due.Value is not null && priority.Value == TodoPriority.High)
.Subscribe(Console.WriteLine);
item.Priority = TodoPriority.High;
// Output:
// False
// True
}
/// <summary>Lists the labels after the title from six properties.</summary>
public static void ProjectTodoTitleWithLabels()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item
.WhenAny(
static x => x.Title,
static x => x.Notes,
static x => x.IsDone,
static x => x.DueDate,
static x => x.Priority,
static x => x.Tags,
static (title, _, _, _, _, tags) => $"{title.Value} #{string.Join(" #", tags.Value)}")
.Subscribe(Console.WriteLine);
item.Tags = _urgentTags;
// Output:
// Renew car registration #errands #car
// Renew car registration #errands #car #urgent
}
/// <summary>Numbers a to-do item from seven properties, every editable property of the item.</summary>
public static void ProjectTodoNumberedHeadline()
{
TodoItem item = CreateRegistrationTask();
using IDisposable subscription = item
.WhenAny(
static x => x.Id,
static x => x.Title,
static x => x.Notes,
static x => x.IsDone,
static x => x.DueDate,
static x => x.Priority,
static x => x.Tags,
static (id, title, _, isDone, _, _, _) => $"{(isDone.Value ? DoneMark : OpenMark)}{id.Value}: {title.Value}")
.Subscribe(Console.WriteLine);
item.Title = RenamedTitle;
item.IsDone = true;
// Output:
// [ ] 7: Renew car registration
// [ ] 7: Renew car registration online
// [x] 7: Renew car registration online
}
/// <summary>Works out from eight properties of a transfer how much money the account keeps after it.</summary>
public static void ProjectTransferRemainingBalance()
{
TransferDraft draft = CreateTransferDraft();
using IDisposable subscription = draft
.WhenAny(
static x => x.Amount,
static x => x.Reference,
static x => x.Source!.Name,
static x => x.Source!.Currency,
static x => x.Source!.Balance,
static x => x.Source!.OverdraftLimit,
static x => x.Source!.AvailableBalance,
static x => x.Payee!,
static (amount, _, _, _, _, _, available, _) => available.Value - amount.Value)
.Subscribe(Console.WriteLine);
draft.Amount = AboveAvailable;
// Output:
// 4450.50
// -4299.50
}
/// <summary>Checks from nine properties whether the account can cover the amount and the payee can receive it.</summary>
public static void ProjectTransferIsPayable()
{
TransferDraft draft = CreateTransferDraft();
using IDisposable subscription = draft
.WhenAny(
static x => x.Amount,
static x => x.Reference,
static x => x.Source!.Name,
static x => x.Source!.Currency,
static x => x.Source!.Balance,
static x => x.Source!.OverdraftLimit,
static x => x.Source!.AvailableBalance,
static x => x.Payee!,
static x => x.Source!.Id,
static (amount, _, _, _, _, _, available, payee, _) => amount.Value <= available.Value && payee.Value.AccountNumber.Length > 0)
.Subscribe(Console.WriteLine);
draft.Amount = AboveAvailable;
// Output:
// True
// False
}
/// <summary>Checks from ten properties whether the amount fits the account and the payee's limit.</summary>
public static void ProjectTransferWithinPayeeLimit()
{
TransferDraft draft = CreateTransferDraft();
using IDisposable subscription = draft
.WhenAny(
static x => x.Amount,
static x => x.Reference,
static x => x.Source!.Name,
static x => x.Source!.Currency,
static x => x.Source!.Balance,
static x => x.Source!.OverdraftLimit,
static x => x.Source!.AvailableBalance,
static x => x.Payee!,
static x => x.Source!.Id,
static x => x.Source!.Kind,
static (amount, _, _, _, _, _, available, payee, _, _) =>
amount.Value <= available.Value && (payee.Value.TransferLimit is not { } max || amount.Value <= max))
.Subscribe(Console.WriteLine);
draft.Amount = AbovePayeeLimit;
// Output:
// True
// False
}
/// <summary>Writes the statement line from eleven properties: the account, the payee and the reference. The payee is replaced as a whole.</summary>
public static void ProjectTransferStatementLine()
{
TransferDraft draft = CreateTransferDraft();
using IDisposable subscription = draft
.WhenAny(
static x => x.Amount,
static x => x.Reference,
static x => x.Source!.Name,
static x => x.Source!.Currency,
static x => x.Source!.Balance,
static x => x.Source!.OverdraftLimit,
static x => x.Source!.AvailableBalance,
static x => x.Payee!,
static x => x.Source!.Id,
static x => x.Source!.Kind,
static x => x.Source!,
static (_, reference, _, _, _, _, _, payee, sourceId, _, _) => $"{sourceId.Value} -> {payee.Value.Name}: {reference.Value}")
.Subscribe(Console.WriteLine);
draft.Reference = RentReferenceRevised;
// Output:
// ACC-1001 -> Harbour Realty: Rent March
// ACC-1001 -> Harbour Realty: Rent March, paid early
}
/// <summary>Flags from twelve properties of the transfer screen, the most one call accepts, a transfer that needs a manual review.</summary>
public static void ProjectTransferNeedsReview()
{
TransferViewModel screen = new(new InMemoryBankingBackend());
TransferDraft draft = screen.Draft;
draft.Source = CreateEverydayAccount();
draft.Payee = _landlord;
draft.Amount = RentAmount;
draft.Reference = RentReference;
using IDisposable subscription = screen
.WhenAny(
static x => x.Draft.Amount,
static x => x.Draft.Reference,
static x => x.Draft.Source!.Name,
static x => x.Draft.Source!.Currency,
static x => x.Draft.Source!.Balance,
static x => x.Draft.Source!.OverdraftLimit,
static x => x.Draft.Source!.AvailableBalance,
static x => x.Draft.Payee!,
static x => x.Draft.Source!.Id,
static x => x.Draft.Source!.Kind,
static x => x.IsValid,
static x => x.ErrorMessage,
static (amount, _, _, _, _, _, available, _, _, kind, _, _) => kind.Value == AccountKind.Savings || amount.Value > available.Value)
.Subscribe(Console.WriteLine);
draft.Source!.Kind = AccountKind.Savings;
// Output:
// False
// True
}
/// <summary>Jumps to the issue number the user types. A number that does not parse throws in the selector, and Catch replaces the failure with a value and ends the pipeline.</summary>
public static void CatchEndsThePipelineAfterOneFailure()
{
InMemoryGitHubServer server = InMemoryGitHubServer.CreateSeeded();
IssueSearchViewModel viewModel = new(server, Webshop) { SearchTerm = FirstIssueNumber };
using IDisposable subscription = viewModel
.WhenAny(static x => x.SearchTerm, static term => int.Parse(term.Value, CultureInfo.InvariantCulture))
.Catch<int, FormatException>(static _ => Signal.Return(NotANumber))
.Subscribe(Console.WriteLine);
viewModel.SearchTerm = SecondIssueNumber;
viewModel.SearchTerm = "abc";
// The pipeline has ended, so this number is never delivered.
viewModel.SearchTerm = ThirdIssueNumber;
// Output:
// 100
// 101
// -1
}
/// <summary>Jumps to the issue number the user types. Handling a number that does not parse inside the selector keeps the pipeline alive.</summary>
public static void HandleFailuresInsideTheSelector()
{
InMemoryGitHubServer server = InMemoryGitHubServer.CreateSeeded();
IssueSearchViewModel viewModel = new(server, Webshop) { SearchTerm = FirstIssueNumber };
using IDisposable subscription = viewModel
.WhenAny(static x => x.SearchTerm, static term => int.TryParse(term.Value, CultureInfo.InvariantCulture, out var number) ? number : NotANumber)
.Subscribe(Console.WriteLine);
viewModel.SearchTerm = SecondIssueNumber;
viewModel.SearchTerm = "abc";
viewModel.SearchTerm = ThirdIssueNumber;
// Output:
// 100
// 101
// -1
// 102
}
/// <summary>Creates the to-do item the examples observe.</summary>
/// <returns>An open, unfinished item.</returns>
private static TodoItem CreateRegistrationTask() => new()
{
Id = RegistrationId,
Title = RegistrationTitle,
Notes = RegistrationNotes,
DueDate = _registrationDue,
Priority = TodoPriority.Normal,
Tags = _registrationTags,
};
/// <summary>Creates the transfer the examples observe.</summary>
/// <returns>A draft that sends the rent from the everyday account to the landlord.</returns>
private static TransferDraft CreateTransferDraft() =>
new() { Source = CreateEverydayAccount(), Payee = _landlord, Amount = RentAmount, Reference = RentReference };
/// <summary>Creates the account the transfer draws on.</summary>
/// <returns>An everyday account with an overdraft.</returns>
private static Account CreateEverydayAccount() => new()
{
Id = EverydayId,
Name = EverydayName,
Kind = AccountKind.Everyday,
Currency = Currency,
Balance = EverydayBalance,
OverdraftLimit = EverydayOverdraft,
};
}