-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathCalculatorViewModel.cs
66 lines (58 loc) · 1.78 KB
/
CalculatorViewModel.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
using Splat;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ReactiveUI.Samples.Basics.ViewModels
{
public class CalculatorViewModel : ReactiveValidatedObject
{
private MemoizingMRUCache<int, int> _cache;
public CalculatorViewModel()
{
_cache = new MemoizingMRUCache<int, int>((x, ctx) =>
{
Thread.Sleep(1000);
// Pretend this calculation isn’t cheap
return x * 10;
}, 5);
CalculateCommand = ReactiveCommand.CreateFromTask(o =>
{
return Task.Factory.StartNew(() =>
{
int top;
bool cached = _cache.TryGet(Number, out top);
if (cached)
{
Result = 0;
Thread.Sleep(1000);
Result = top;
}
else
{
top = _cache.Get(Number);
for (int i = 0; i <= top; i++)
{
Result = i;
Thread.Sleep(100);
}
}
});
});
}
private int _Number;
[Required]
public int Number
{
get { return _Number; }
set { this.RaiseAndSetIfChanged(ref _Number, value); }
}
public ICommand CalculateCommand { get; set; }
private int _Result;
public int Result
{
get { return _Result; }
set { this.RaiseAndSetIfChanged(ref _Result, value); }
}
}
}