-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ReactiveCommand.cs
executable file
·1187 lines (1091 loc) · 50.4 KB
/
ReactiveCommand.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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reactive.Threading.Tasks;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ReactiveUI
{
/// <summary>
/// Encapsulates a user action behind a reactive interface.
/// </summary>
/// <remarks>
/// <para>
/// This non-generic base class defines the base behavior for all reactive commands.
/// </para>
/// <para>
/// Reactive commands encapsulate the behavior of running some execution logic and then surfacing the results on the UI
/// thread. Importantly, no scheduling is performed against input observables (the <c>canExecute</c> and execution pipelines).
/// </para>
/// <para>
/// To create an instance of <c>ReactiveCommand</c>, call one of the static creation methods defined by this class.
/// <see cref="Create"/> can be used when your execution logic is synchronous.
/// <see cref="CreateFromObservable{TResult}(Func{IObservable{TResult}}, IObservable{bool}, IScheduler)"/> and
/// <see cref="CreateFromTask(Func{Task}, IObservable{bool}, IScheduler)"/> (and overloads) can be used for asynchronous
/// execution logic. Optionally, you can provide an observable that governs the availability of the command for execution,
/// as well as a scheduler to which events will be delivered.
/// </para>
/// <para>
/// The <see cref="CanExecute"/> property provides an observable that can be used to determine whether the command is
/// eligible for execution. The value of this observable is determined by both the <c>canExecute</c> observable provided
/// during command creation, and the current execution status of the command. A command that is already executing will
/// yield <c>false</c> from its <see cref="CanExecute"/> observable regardless of the <c>canExecute</c> observable provided
/// during command creation.
/// </para>
/// <para>
/// The <see cref="IsExecuting"/> property provides an observable whose value indicates whether the command is currently
/// executing. This can be a useful means of triggering UI, such as displaying an activity indicator whilst a command is
/// executing.
/// </para>
/// <para>
/// As discussed above, you are under no obligation to somehow incorporate this into your <c>canExecute</c> observable
/// because that is taken care of for you. That is, if the value of <c>IsExecuting</c> is <c>true</c>, the value of
/// <c>CanExecute</c> will be <c>false</c>. However, if the value of <c>CanExecute</c> is <c>false</c>, that does not imply
/// the value of <c>IsExecuting</c> is <c>true</c>.
/// </para>
/// <para>
/// Any errors in your command's execution logic (including any <c>canExecute</c> observable you choose to provide) will be
/// surfaced via the <see cref="ThrownExceptions"/> observable. This gives you the opportunity to handle the error before
/// it triggers a default handler that tears down the application. For example, you might use this as a means of alerting
/// the user that something has gone wrong executing the command.
/// </para>
/// <para>
/// For the sake of convenience, all <c>ReactiveCommand</c> instances are also implementations of <see cref="ICommand"/>.
/// This allows you to easily integrate instances of <c>ReactiveCommand</c> into platforms that understands <c>ICommand</c>
/// natively (such as WPF and UWP).
/// </para>
/// </remarks>
public abstract partial class ReactiveCommand
{
/// <summary>
/// Creates a parameterless <see cref="ReactiveCommand{TParam, TResult}"/> with synchronous execution logic.
/// </summary>
/// <param name="execute">
/// The action to execute whenever the command is executed.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
public static ReactiveCommand<Unit, Unit> Create(
Action execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
if (execute == null) {
throw new ArgumentNullException("execute");
}
return new ReactiveCommand<Unit, Unit>(
_ => Observable.Create<Unit>(
observer => {
execute();
observer.OnNext(Unit.Default);
observer.OnCompleted();
return Disposable.Empty;
}),
canExecute ?? Observables.True,
outputScheduler ?? RxApp.MainThreadScheduler);
}
/// <summary>
/// Creates a parameterless <see cref="ReactiveCommand{TParam, TResult}"/> with synchronous execution logic that returns a value
/// of type <typeparamref name="TResult"/>.
/// </summary>
/// <param name="execute">
/// The function to execute whenever the command is executed.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TResult">
/// The type of value returned by command executions.
/// </typeparam>
public static ReactiveCommand<Unit, TResult> Create<TResult>(
Func<TResult> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
if (execute == null) {
throw new ArgumentNullException("execute");
}
return new ReactiveCommand<Unit, TResult>(
_ => Observable.Create<TResult>(
observer => {
observer.OnNext(execute());
observer.OnCompleted();
return Disposable.Empty;
}),
canExecute ?? Observables.True,
outputScheduler ?? RxApp.MainThreadScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with synchronous execution logic that takes a parameter of type <typeparamref name="TParam"/>.
/// </summary>
/// <param name="execute">
/// The action to execute whenever the command is executed.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
public static ReactiveCommand<TParam, Unit> Create<TParam>(
Action<TParam> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
if (execute == null) {
throw new ArgumentNullException("execute");
}
return new ReactiveCommand<TParam, Unit>(
param => Observable.Create<Unit>(
observer => {
execute(param);
observer.OnNext(Unit.Default);
observer.OnCompleted();
return Disposable.Empty;
}),
canExecute ?? Observables.True,
outputScheduler ?? RxApp.MainThreadScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with synchronous execution logic that takes a parameter of type <typeparamref name="TParam"/>
/// and returns a value of type <typeparamref name="TResult"/>.
/// </summary>
/// <param name="execute">
/// The function to execute whenever the command is executed.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of value returned by command executions.
/// </typeparam>
public static ReactiveCommand<TParam, TResult> Create<TParam, TResult>(
Func<TParam, TResult> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
if (execute == null) {
throw new ArgumentNullException("execute");
}
return new ReactiveCommand<TParam, TResult>(
param => Observable.Create<TResult>(
observer => {
observer.OnNext(execute(param));
observer.OnCompleted();
return Disposable.Empty;
}),
canExecute ?? Observables.True,
outputScheduler ?? RxApp.MainThreadScheduler);
}
/// <summary>
/// Creates a parameterless <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic.
/// </summary>
/// <param name="execute">
/// Provides an observable representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static ReactiveCommand<Unit, TResult> CreateFromObservable<TResult>(
Func<IObservable<TResult>> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
if (execute == null) {
throw new ArgumentNullException("execute");
}
return new ReactiveCommand<Unit, TResult>(
_ => execute(),
canExecute ?? Observables.True,
outputScheduler ?? RxApp.MainThreadScheduler);
}
/// <summary>
/// Creates a parameterless <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static ReactiveCommand<Unit, TResult> CreateFromTask<TResult>(
Func<Task<TResult>> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable(
() => execute().ToObservable(),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a parameterless, cancellable <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static ReactiveCommand<Unit, TResult> CreateFromTask<TResult>(
Func<CancellationToken, Task<TResult>> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable(
() => Observable.StartAsync(ct => execute(ct)),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a parameterless <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
public static ReactiveCommand<Unit, Unit> CreateFromTask(
Func<Task> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable(
() => execute().ToObservable(),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a parameterless, cancellable <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
public static ReactiveCommand<Unit, Unit> CreateFromTask(
Func<CancellationToken, Task> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable(
() => Observable.StartAsync(ct => execute(ct)),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic that takes a parameter of type <typeparamref name="TParam"/>.
/// </summary>
/// <param name="execute">
/// Provides an observable representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static ReactiveCommand<TParam, TResult> CreateFromObservable<TParam, TResult>(
Func<TParam, IObservable<TResult>> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return new ReactiveCommand<TParam, TResult>(
execute,
canExecute ?? Observables.True,
outputScheduler ?? RxApp.MainThreadScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic that takes a parameter of type <typeparamref name="TParam"/>.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static ReactiveCommand<TParam, TResult> CreateFromTask<TParam, TResult>(
Func<TParam, Task<TResult>> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable<TParam, TResult>(
param => execute(param).ToObservable(),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous, cancellable execution logic that takes a parameter of type <typeparamref name="TParam"/>.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static ReactiveCommand<TParam, TResult> CreateFromTask<TParam, TResult>(
Func<TParam, CancellationToken, Task<TResult>> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable<TParam, TResult>(
param => Observable.StartAsync(ct => execute(param, ct)),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous execution logic that takes a parameter of type <typeparamref name="TParam"/>.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
public static ReactiveCommand<TParam, Unit> CreateFromTask<TParam>(
Func<TParam, Task> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable<TParam, Unit>(
param => execute(param).ToObservable(),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a <see cref="ReactiveCommand{TParam, TResult}"/> with asynchronous, cancellable execution logic that takes a parameter of type <typeparamref name="TParam"/>.
/// </summary>
/// <param name="execute">
/// Provides a <see cref="Task"/> representing the command's asynchronous execution logic.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution.
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>ReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
public static ReactiveCommand<TParam, Unit> CreateFromTask<TParam>(
Func<TParam, CancellationToken, Task> execute,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return CreateFromObservable<TParam, Unit>(
param => Observable.StartAsync(ct => execute(param, ct)),
canExecute,
outputScheduler);
}
/// <summary>
/// Creates a <see cref="CombinedReactiveCommand{TParam, TResult}"/> that composes all the provided child commands.
/// </summary>
/// <param name="childCommands">
/// The child commands that the combined command will compose.
/// </param>
/// <param name="canExecute">
/// An optional observable that dictates the availability of the command for execution (in addition to the availability specified
/// by each individual child command).
/// </param>
/// <param name="outputScheduler">
/// An optional scheduler that is used to surface events. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </param>
/// <returns>
/// The <c>CombinedReactiveCommand</c> instance.
/// </returns>
/// <typeparam name="TParam">
/// The type of the parameter passed through to command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the command's result.
/// </typeparam>
public static CombinedReactiveCommand<TParam, TResult> CreateCombined<TParam, TResult>(
IEnumerable<ReactiveCommandBase<TParam, TResult>> childCommands,
IObservable<bool> canExecute = null,
IScheduler outputScheduler = null)
{
return new CombinedReactiveCommand<TParam, TResult>(childCommands, canExecute ?? Observables.True, outputScheduler ?? RxApp.MainThreadScheduler);
}
}
// non-generic reactive command functionality
public abstract partial class ReactiveCommand : IDisposable, ICommand, IHandleObservableErrors
{
private EventHandler canExecuteChanged;
/// <summary>
/// An observable whose value indicates whether the command can currently execute.
/// </summary>
/// <remarks>
/// The value provided by this observable is governed both by any <c>canExecute</c> observable provided during
/// command creation, as well as the current execution status of the command. A command that is currently executing
/// will always yield <c>false</c> from this observable, even if the <c>canExecute</c> pipeline is currently <c>true</c>.
/// </remarks>
public abstract IObservable<bool> CanExecute
{
get;
}
/// <summary>
/// An observable whose value indicates whether the command is currently executing.
/// </summary>
/// <remarks>
/// This observable can be particularly useful for updating UI, such as showing an activity indicator whilst a command
/// is executing.
/// </remarks>
public abstract IObservable<bool> IsExecuting
{
get;
}
/// <summary>
/// An observable that ticks any exceptions in command execution logic.
/// </summary>
/// <remarks>
/// Any exceptions that are not observed via this observable will propagate out and cause the application to be torn
/// down. Therefore, you will always want to subscribe to this observable if you expect errors could occur (e.g. if
/// your command execution includes network activity).
/// </remarks>
public abstract IObservable<Exception> ThrownExceptions
{
get;
}
/// <summary>
/// Disposes of this <c>ReactiveCommand</c>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
protected abstract void Dispose(bool disposing);
event EventHandler ICommand.CanExecuteChanged
{
add { this.canExecuteChanged += value; }
remove { this.canExecuteChanged -= value; }
}
bool ICommand.CanExecute(object parameter)
{
return this.ICommandCanExecute(parameter);
}
void ICommand.Execute(object parameter)
{
this.ICommandExecute(parameter);
}
protected abstract bool ICommandCanExecute(object parameter);
protected abstract void ICommandExecute(object parameter);
protected void OnCanExecuteChanged()
{
var handler = this.canExecuteChanged;
if (handler != null) {
handler(this, EventArgs.Empty);
}
}
}
/// <summary>
/// A base class for generic reactive commands.
/// </summary>
/// <remarks>
/// <para>
/// This class extends <see cref="ReactiveCommand"/> and adds generic type parameters for the parameter values passed
/// into command execution, and the return values of command execution.
/// </para>
/// <para>
/// Because the result type is known by this class, it can implement <see cref="IObservable{T}"/>. However, the implementation
/// is defined as abstract, so subclasses must provide it.
/// </para>
/// </remarks>
/// <typeparam name="TParam">
/// The type of parameter values passed in during command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the values that are the result of command execution.
/// </typeparam>
public abstract class ReactiveCommandBase<TParam, TResult> : ReactiveCommand, IObservable<TResult>
{
/// <summary>
/// Subscribes to execution results from this command.
/// </summary>
/// <param name="observer">
/// The observer.
/// </param>
/// <returns>
/// An <see cref="IDisposable"/> that, when disposed, will unsubscribe the observer.
/// </returns>
public abstract IDisposable Subscribe(IObserver<TResult> observer);
/// <summary>
/// Gets an observable that, when subscribed, executes this command.
/// </summary>
/// <remarks>
/// <para>
/// Invoking this method will return a cold (lazy) observable that, when subscribed, will execute the logic
/// encapsulated by the command. It is worth restating that the returned observable is lazy. Nothing will
/// happen if you call <c>Execute</c> and neglect to subscribe (directly or indirectly) to the returned observable.
/// </para>
/// <para>
/// If no parameter value is provided, a default value of type <typeparamref name="TParam"/> will be passed into
/// the execution logic.
/// </para>
/// <para>
/// Any number of subscribers can subscribe to a given execution observable and the execution logic will only
/// run once. That is, the result is broadcast to those subscribers.
/// </para>
/// <para>
/// In those cases where execution fails, there will be no result value. Instead, the failure will tick through the
/// <see cref="ReactiveCommand.ThrownExceptions"/> observable.
/// </para>
/// </remarks>
/// <param name="parameter">
/// The parameter to pass into command execution.
/// </param>
/// <returns>
/// An observable that will tick the single result value if and when it becomes available.
/// </returns>
public abstract IObservable<TResult> Execute(TParam parameter = default(TParam));
protected override bool ICommandCanExecute(object parameter)
{
return this.CanExecute.FirstAsync().Wait();
}
protected override void ICommandExecute(object parameter)
{
// ensure that null is coerced to default(TParam) so that commands taking value types will use a sensible default if no parameter is supplied
if (parameter == null) {
parameter = default(TParam);
}
if (parameter != null && !(parameter is TParam)) {
throw new InvalidOperationException(
String.Format(
"Command requires parameters of type {0}, but received parameter of type {1}.",
typeof(TParam).FullName,
parameter.GetType().FullName));
}
this
.Execute((TParam)parameter)
.Catch(Observable<TResult>.Empty)
.Subscribe();
}
}
/// <summary>
/// Encapsulates a user interaction behind a reactive interface.
/// </summary>
/// <remarks>
/// <para>
/// This class provides the bulk of the actual implementation for reactive commands. You should not create instances
/// of this class directly, but rather via the static creation methods on the non-generic <see cref="ReactiveCommand"/>
/// class.
/// </para>
/// </remarks>
/// <typeparam name="TParam">
/// The type of parameter values passed in during command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the values that are the result of command execution.
/// </typeparam>
public class ReactiveCommand<TParam, TResult> : ReactiveCommandBase<TParam, TResult>
{
private readonly Func<TParam, IObservable<TResult>> execute;
private readonly IScheduler outputScheduler;
private readonly Subject<ExecutionInfo> executionInfo;
private readonly ISubject<ExecutionInfo, ExecutionInfo> synchronizedExecutionInfo;
private readonly IObservable<bool> isExecuting;
private readonly IObservable<bool> canExecute;
private readonly IObservable<TResult> results;
private readonly ScheduledSubject<Exception> exceptions;
private readonly IDisposable canExecuteSubscription;
internal protected ReactiveCommand(
Func<TParam, IObservable<TResult>> execute,
IObservable<bool> canExecute,
IScheduler outputScheduler)
{
if (execute == null) {
throw new ArgumentNullException("execute");
}
if (canExecute == null) {
throw new ArgumentNullException("canExecute");
}
if (outputScheduler == null) {
throw new ArgumentNullException("outputScheduler");
}
this.execute = execute;
this.outputScheduler = outputScheduler;
this.executionInfo = new Subject<ExecutionInfo>();
this.synchronizedExecutionInfo = Subject.Synchronize(this.executionInfo, outputScheduler);
this.isExecuting = this
.synchronizedExecutionInfo
.Scan(
0,
(acc, next) => {
if (next.Demarcation == ExecutionDemarcation.Begin) {
return acc + 1;
}
if (next.Demarcation == ExecutionDemarcation.End) {
return acc - 1;
}
return acc;
})
.Select(inFlightCount => inFlightCount > 0)
.StartWith(false)
.DistinctUntilChanged()
.Replay(1)
.RefCount();
this.canExecute = canExecute
.Catch<bool, Exception>(ex => {
this.exceptions.OnNext(ex);
return Observables.False;
})
.StartWith(false)
.CombineLatest(this.isExecuting, (canEx, isEx) => canEx && !isEx)
.DistinctUntilChanged()
.Replay(1)
.RefCount();
this.results = this
.synchronizedExecutionInfo
.Where(x => x.Demarcation == ExecutionDemarcation.Result)
.Select(x => x.Result);
this.exceptions = new ScheduledSubject<Exception>(outputScheduler, RxApp.DefaultExceptionHandler);
this.canExecuteSubscription = this
.canExecute
.Subscribe(_ => this.OnCanExecuteChanged());
}
/// <inheritdoc/>
public override IObservable<bool> CanExecute
{
get { return this.canExecute; }
}
/// <inheritdoc/>
public override IObservable<bool> IsExecuting
{
get { return this.isExecuting; }
}
/// <inheritdoc/>
public override IObservable<Exception> ThrownExceptions
{
get { return this.exceptions.AsObservable(); }
}
/// <inheritdoc/>
public override IDisposable Subscribe(IObserver<TResult> observer)
{
return results.Subscribe(observer);
}
/// <inheritdoc/>
public override IObservable<TResult> Execute(TParam parameter = default(TParam))
{
try {
return Observable
.Defer(
() => {
this.synchronizedExecutionInfo.OnNext(ExecutionInfo.CreateBegin());
return Observable<TResult>.Empty;
})
.Concat(this.execute(parameter))
.Do(result => this.synchronizedExecutionInfo.OnNext(ExecutionInfo.CreateResult(result)))
.Catch<TResult, Exception>(
ex => {
exceptions.OnNext(ex);
return Observable.Throw<TResult>(ex);
})
.Finally(() => this.synchronizedExecutionInfo.OnNext(ExecutionInfo.CreateEnd()))
.PublishLast()
.RefCount()
.ObserveOn(this.outputScheduler);
} catch (Exception ex) {
this.exceptions.OnNext(ex);
return Observable.Throw<TResult>(ex);
}
}
protected override void Dispose(bool disposing)
{
if (disposing) {
this.executionInfo.Dispose();
this.exceptions.Dispose();
this.canExecuteSubscription.Dispose();
}
}
private enum ExecutionDemarcation
{
Begin,
Result,
End
}
private struct ExecutionInfo
{
private readonly ExecutionDemarcation demarcation;
private readonly TResult result;
private ExecutionInfo(ExecutionDemarcation demarcation, TResult result)
{
this.demarcation = demarcation;
this.result = result;
}
public ExecutionDemarcation Demarcation => this.demarcation;
public TResult Result => this.result;
public static ExecutionInfo CreateBegin() =>
new ExecutionInfo(ExecutionDemarcation.Begin, default(TResult));
public static ExecutionInfo CreateResult(TResult result) =>
new ExecutionInfo(ExecutionDemarcation.Result, result);
public static ExecutionInfo CreateEnd() =>
new ExecutionInfo(ExecutionDemarcation.End, default(TResult));
}
}
/// <summary>
/// Encapsulates a composite user interaction.
/// </summary>
/// <remarks>
/// <para>
/// This class provides the bulk of the actual implementation for combined reactive commands. You should not
/// create instances of this class directly, but rather via the static creation methods on the non-generic
/// <see cref="ReactiveCommand"/> class.
/// </para>
/// <para>
/// A <c>CombinedReactiveCommand</c> combines multiple reactive commands into a single command. Executing
/// the combined command executes all child commands. Since all child commands will receive the same execution
/// parameter, all child commands must accept a parameter of the same type.
/// </para>
/// <para>
/// In order for the combined command to be executable, all child commands must themselves be executable.
/// In addition, any <c>canExecute</c> observable passed in during construction must also yield <c>true</c>.
/// </para>
/// </remarks>
/// <typeparam name="TParam">
/// The type of parameter values passed in during command execution.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the values that are the result of command execution.
/// </typeparam>
public class CombinedReactiveCommand<TParam, TResult> : ReactiveCommandBase<TParam, IList<TResult>>
{
private readonly ReactiveCommand<TParam, IList<TResult>> innerCommand;
private readonly ScheduledSubject<Exception> exceptions;
private readonly IDisposable exceptionsSubscription;
internal protected CombinedReactiveCommand(
IEnumerable<ReactiveCommandBase<TParam, TResult>> childCommands,
IObservable<bool> canExecute,
IScheduler outputScheduler)
{
if (childCommands == null) {
throw new ArgumentNullException("childCommands");
}
if (canExecute == null) {
throw new ArgumentNullException("canExecute");
}
if (outputScheduler == null) {
throw new ArgumentNullException("outputScheduler");
}
var childCommandsArray = childCommands.ToArray();
if (childCommandsArray.Length == 0) {
throw new ArgumentException("No child commands provided.", "childCommands");
}
var canChildrenExecute = Observable
.CombineLatest(childCommandsArray.Select(x => x.CanExecute))
.Select(x => x.All(y => y));
var combinedCanExecute = canExecute
.Catch<bool, Exception>(ex => {
this.exceptions.OnNext(ex);
return Observables.False;
})
.StartWith(false)
.CombineLatest(canChildrenExecute, (ce, cce) => ce && cce)
.DistinctUntilChanged()
.Replay(1)
.RefCount();
this.exceptionsSubscription = Observable
.Merge(childCommandsArray.Select(x => x.ThrownExceptions))
.Subscribe(ex => this.exceptions.OnNext(ex));
this.innerCommand = new ReactiveCommand<TParam, IList<TResult>>(
param =>
Observable
.CombineLatest(
childCommandsArray
.Select(x => x.Execute(param))),
combinedCanExecute,
outputScheduler);
// we already handle exceptions on individual child commands above, but the same exception
// will tick through innerCommand. Therefore, we need to ensure we ignore it or the default
// handler will execute and the process will be torn down
this.innerCommand
.ThrownExceptions
.Subscribe();
this.exceptions = new ScheduledSubject<Exception>(outputScheduler, RxApp.DefaultExceptionHandler);