-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObservableCommand.cs
More file actions
101 lines (84 loc) · 2.51 KB
/
Copy pathObservableCommand.cs
File metadata and controls
101 lines (84 loc) · 2.51 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
using System;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Windows.Input;
namespace MondoUniversalWindowsSample
{
public sealed class ObservableCommand : ObservableCommand<Unit>
{
public ObservableCommand(IObservable<bool> canExecute) : base(canExecute)
{
}
public ObservableCommand()
{
}
}
public class ObservableCommand<TParam> : ICommand, IDisposable, IObservable<TParam>
{
private readonly BehaviorSubject<bool> _canExecuteSubject = new BehaviorSubject<bool>(false);
private readonly Subject<TParam> _values = new Subject<TParam>();
private readonly IDisposable _subscription;
private readonly Func<TParam, bool> _canExecuteFunc;
private bool _enabled = true;
public ObservableCommand(IObservable<bool> canExecute)
{
_subscription = canExecute
.Subscribe(value =>
{
_canExecuteSubject.OnNext(value);
OnCanExecuteChanged();
});
}
public ObservableCommand(Func<TParam, bool> canExecuteFunc)
{
_canExecuteFunc = canExecuteFunc;
}
public ObservableCommand()
: this(Observable.Return(true))
{
}
public bool CanExecute(object parameter)
{
if (!_enabled)
{
return false;
}
if (_canExecuteFunc != null)
{
return _canExecuteFunc((TParam)parameter);
}
return _canExecuteSubject.First();
}
public void Execute(object parameter)
{
TParam paramValue = (parameter == null)
? default(TParam)
: (TParam)parameter;
_values.OnNext(paramValue);
}
protected void OnCanExecuteChanged()
{
var handler = CanExecuteChanged;
handler?.Invoke(this, EventArgs.Empty);
}
public event EventHandler CanExecuteChanged;
public void Dispose()
{
_subscription.Dispose();
}
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
OnCanExecuteChanged();
}
}
public IDisposable Subscribe(IObserver<TParam> observer)
{
return _values.Subscribe(observer);
}
}
}