ReactiveCommand.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. #if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
  5. using System.Threading.Tasks;
  6. using UniRx.InternalUtil;
  7. #endif
  8. namespace UniRx
  9. {
  10. public interface IReactiveCommand<T> : IObservable<T>
  11. {
  12. IReadOnlyReactiveProperty<bool> CanExecute { get; }
  13. bool Execute(T parameter);
  14. }
  15. public interface IAsyncReactiveCommand<T>
  16. {
  17. IReadOnlyReactiveProperty<bool> CanExecute { get; }
  18. IDisposable Execute(T parameter);
  19. IDisposable Subscribe(Func<T, IObservable<Unit>> asyncAction);
  20. }
  21. /// <summary>
  22. /// Represents ReactiveCommand&lt;Unit&gt;
  23. /// </summary>
  24. public class ReactiveCommand : ReactiveCommand<Unit>
  25. {
  26. /// <summary>
  27. /// CanExecute is always true.
  28. /// </summary>
  29. public ReactiveCommand()
  30. : base()
  31. { }
  32. /// <summary>
  33. /// CanExecute is changed from canExecute sequence.
  34. /// </summary>
  35. public ReactiveCommand(IObservable<bool> canExecuteSource, bool initialValue = true)
  36. : base(canExecuteSource, initialValue)
  37. {
  38. }
  39. /// <summary>Push null to subscribers.</summary>
  40. public bool Execute()
  41. {
  42. return Execute(Unit.Default);
  43. }
  44. /// <summary>Force push parameter to subscribers.</summary>
  45. public void ForceExecute()
  46. {
  47. ForceExecute(Unit.Default);
  48. }
  49. }
  50. public class ReactiveCommand<T> : IReactiveCommand<T>, IDisposable
  51. {
  52. readonly Subject<T> trigger = new Subject<T>();
  53. readonly IDisposable canExecuteSubscription;
  54. ReactiveProperty<bool> canExecute;
  55. public IReadOnlyReactiveProperty<bool> CanExecute
  56. {
  57. get
  58. {
  59. return canExecute;
  60. }
  61. }
  62. public bool IsDisposed { get; private set; }
  63. /// <summary>
  64. /// CanExecute is always true.
  65. /// </summary>
  66. public ReactiveCommand()
  67. {
  68. this.canExecute = new ReactiveProperty<bool>(true);
  69. this.canExecuteSubscription = Disposable.Empty;
  70. }
  71. /// <summary>
  72. /// CanExecute is changed from canExecute sequence.
  73. /// </summary>
  74. public ReactiveCommand(IObservable<bool> canExecuteSource, bool initialValue = true)
  75. {
  76. this.canExecute = new ReactiveProperty<bool>(initialValue);
  77. this.canExecuteSubscription = canExecuteSource
  78. .DistinctUntilChanged()
  79. .SubscribeWithState(canExecute, (b, c) => c.Value = b);
  80. }
  81. /// <summary>Push parameter to subscribers when CanExecute.</summary>
  82. public bool Execute(T parameter)
  83. {
  84. if (canExecute.Value)
  85. {
  86. trigger.OnNext(parameter);
  87. return true;
  88. }
  89. else
  90. {
  91. return false;
  92. }
  93. }
  94. /// <summary>Force push parameter to subscribers.</summary>
  95. public void ForceExecute(T parameter)
  96. {
  97. trigger.OnNext(parameter);
  98. }
  99. /// <summary>Subscribe execute.</summary>
  100. public IDisposable Subscribe(IObserver<T> observer)
  101. {
  102. return trigger.Subscribe(observer);
  103. }
  104. /// <summary>
  105. /// Stop all subscription and lock CanExecute is false.
  106. /// </summary>
  107. public void Dispose()
  108. {
  109. if (IsDisposed) return;
  110. IsDisposed = true;
  111. canExecute.Dispose();
  112. trigger.OnCompleted();
  113. trigger.Dispose();
  114. canExecuteSubscription.Dispose();
  115. }
  116. }
  117. /// <summary>
  118. /// Variation of ReactiveCommand, when executing command then CanExecute = false after CanExecute = true.
  119. /// </summary>
  120. public class AsyncReactiveCommand : AsyncReactiveCommand<Unit>
  121. {
  122. /// <summary>
  123. /// CanExecute is automatically changed when executing to false and finished to true.
  124. /// </summary>
  125. public AsyncReactiveCommand()
  126. : base()
  127. {
  128. }
  129. /// <summary>
  130. /// CanExecute is automatically changed when executing to false and finished to true.
  131. /// </summary>
  132. public AsyncReactiveCommand(IObservable<bool> canExecuteSource)
  133. : base(canExecuteSource)
  134. {
  135. }
  136. /// <summary>
  137. /// CanExecute is automatically changed when executing to false and finished to true.
  138. /// The source is shared between other AsyncReactiveCommand.
  139. /// </summary>
  140. public AsyncReactiveCommand(IReactiveProperty<bool> sharedCanExecute)
  141. : base(sharedCanExecute)
  142. {
  143. }
  144. public IDisposable Execute()
  145. {
  146. return base.Execute(Unit.Default);
  147. }
  148. }
  149. /// <summary>
  150. /// Variation of ReactiveCommand, canExecute is changed when executing command then CanExecute = false after CanExecute = true.
  151. /// </summary>
  152. public class AsyncReactiveCommand<T> : IAsyncReactiveCommand<T>
  153. {
  154. UniRx.InternalUtil.ImmutableList<Func<T, IObservable<Unit>>> asyncActions = UniRx.InternalUtil.ImmutableList<Func<T, IObservable<Unit>>>.Empty;
  155. readonly object gate = new object();
  156. readonly IReactiveProperty<bool> canExecuteSource;
  157. readonly IReadOnlyReactiveProperty<bool> canExecute;
  158. public IReadOnlyReactiveProperty<bool> CanExecute
  159. {
  160. get
  161. {
  162. return canExecute;
  163. }
  164. }
  165. public bool IsDisposed { get; private set; }
  166. /// <summary>
  167. /// CanExecute is automatically changed when executing to false and finished to true.
  168. /// </summary>
  169. public AsyncReactiveCommand()
  170. {
  171. this.canExecuteSource = new ReactiveProperty<bool>(true);
  172. this.canExecute = canExecuteSource;
  173. }
  174. /// <summary>
  175. /// CanExecute is automatically changed when executing to false and finished to true.
  176. /// </summary>
  177. public AsyncReactiveCommand(IObservable<bool> canExecuteSource)
  178. {
  179. this.canExecuteSource = new ReactiveProperty<bool>(true);
  180. this.canExecute = this.canExecuteSource.CombineLatest(canExecuteSource, (x, y) => x && y).ToReactiveProperty();
  181. }
  182. /// <summary>
  183. /// CanExecute is automatically changed when executing to false and finished to true.
  184. /// The source is shared between other AsyncReactiveCommand.
  185. /// </summary>
  186. public AsyncReactiveCommand(IReactiveProperty<bool> sharedCanExecute)
  187. {
  188. this.canExecuteSource = sharedCanExecute;
  189. this.canExecute = sharedCanExecute;
  190. }
  191. /// <summary>Push parameter to subscribers when CanExecute.</summary>
  192. public IDisposable Execute(T parameter)
  193. {
  194. if (canExecute.Value)
  195. {
  196. canExecuteSource.Value = false;
  197. var a = asyncActions.Data;
  198. if (a.Length == 1)
  199. {
  200. try
  201. {
  202. var asyncState = a[0].Invoke(parameter) ?? Observable.ReturnUnit();
  203. return asyncState.Finally(() => canExecuteSource.Value = true).Subscribe();
  204. }
  205. catch
  206. {
  207. canExecuteSource.Value = true;
  208. throw;
  209. }
  210. }
  211. else
  212. {
  213. var xs = new IObservable<Unit>[a.Length];
  214. try
  215. {
  216. for (int i = 0; i < a.Length; i++)
  217. {
  218. xs[i] = a[i].Invoke(parameter) ?? Observable.ReturnUnit();
  219. }
  220. }
  221. catch
  222. {
  223. canExecuteSource.Value = true;
  224. throw;
  225. }
  226. return Observable.WhenAll(xs).Finally(() => canExecuteSource.Value = true).Subscribe();
  227. }
  228. }
  229. else
  230. {
  231. return Disposable.Empty;
  232. }
  233. }
  234. /// <summary>Subscribe execute.</summary>
  235. public IDisposable Subscribe(Func<T, IObservable<Unit>> asyncAction)
  236. {
  237. lock (gate)
  238. {
  239. asyncActions = asyncActions.Add(asyncAction);
  240. }
  241. return new Subscription(this, asyncAction);
  242. }
  243. /// <summary>
  244. /// Stop all subscription and lock CanExecute is false.
  245. /// </summary>
  246. public void Dispose()
  247. {
  248. if (IsDisposed) return;
  249. IsDisposed = true;
  250. asyncActions = UniRx.InternalUtil.ImmutableList<Func<T, IObservable<Unit>>>.Empty;
  251. }
  252. class Subscription : IDisposable
  253. {
  254. readonly AsyncReactiveCommand<T> parent;
  255. readonly Func<T, IObservable<Unit>> asyncAction;
  256. public Subscription(AsyncReactiveCommand<T> parent, Func<T, IObservable<Unit>> asyncAction)
  257. {
  258. this.parent = parent;
  259. this.asyncAction = asyncAction;
  260. }
  261. public void Dispose()
  262. {
  263. lock (parent.gate)
  264. {
  265. parent.asyncActions = parent.asyncActions.Remove(asyncAction);
  266. }
  267. }
  268. }
  269. }
  270. public static class ReactiveCommandExtensions
  271. {
  272. /// <summary>
  273. /// Create non parameter commands. CanExecute is changed from canExecute sequence.
  274. /// </summary>
  275. public static ReactiveCommand ToReactiveCommand(this IObservable<bool> canExecuteSource, bool initialValue = true)
  276. {
  277. return new ReactiveCommand(canExecuteSource, initialValue);
  278. }
  279. /// <summary>
  280. /// Create parametered comamnds. CanExecute is changed from canExecute sequence.
  281. /// </summary>
  282. public static ReactiveCommand<T> ToReactiveCommand<T>(this IObservable<bool> canExecuteSource, bool initialValue = true)
  283. {
  284. return new ReactiveCommand<T>(canExecuteSource, initialValue);
  285. }
  286. #if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
  287. static readonly Action<object> Callback = CancelCallback;
  288. static void CancelCallback(object state)
  289. {
  290. var tuple = (Tuple<ICancellableTaskCompletionSource, IDisposable>)state;
  291. tuple.Item2.Dispose();
  292. tuple.Item1.TrySetCanceled();
  293. }
  294. public static Task<T> WaitUntilExecuteAsync<T>(this IReactiveCommand<T> source, CancellationToken cancellationToken = default(CancellationToken))
  295. {
  296. var tcs = new CancellableTaskCompletionSource<T>();
  297. var disposable = new SingleAssignmentDisposable();
  298. disposable.Disposable = source.Subscribe(x =>
  299. {
  300. disposable.Dispose(); // finish subscription.
  301. tcs.TrySetResult(x);
  302. }, ex => tcs.TrySetException(ex), () => tcs.TrySetCanceled());
  303. cancellationToken.Register(Callback, Tuple.Create(tcs, disposable.Disposable), false);
  304. return tcs.Task;
  305. }
  306. public static System.Runtime.CompilerServices.TaskAwaiter<T> GetAwaiter<T>(this IReactiveCommand<T> command)
  307. {
  308. return command.WaitUntilExecuteAsync(CancellationToken.None).GetAwaiter();
  309. }
  310. #endif
  311. #if !UniRxLibrary
  312. // for uGUI(from 4.6)
  313. #if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5)
  314. /// <summary>
  315. /// Bind ReactiveCommand to button's interactable and onClick.
  316. /// </summary>
  317. public static IDisposable BindTo(this IReactiveCommand<Unit> command, UnityEngine.UI.Button button)
  318. {
  319. var d1 = command.CanExecute.SubscribeToInteractable(button);
  320. var d2 = button.OnClickAsObservable().SubscribeWithState(command, (x, c) => c.Execute(x));
  321. return StableCompositeDisposable.Create(d1, d2);
  322. }
  323. /// <summary>
  324. /// Bind ReactiveCommand to button's interactable and onClick and register onClick action to command.
  325. /// </summary>
  326. public static IDisposable BindToOnClick(this IReactiveCommand<Unit> command, UnityEngine.UI.Button button, Action<Unit> onClick)
  327. {
  328. var d1 = command.CanExecute.SubscribeToInteractable(button);
  329. var d2 = button.OnClickAsObservable().SubscribeWithState(command, (x, c) => c.Execute(x));
  330. var d3 = command.Subscribe(onClick);
  331. return StableCompositeDisposable.Create(d1, d2, d3);
  332. }
  333. /// <summary>
  334. /// Bind canExecuteSource to button's interactable and onClick and register onClick action to command.
  335. /// </summary>
  336. public static IDisposable BindToButtonOnClick(this IObservable<bool> canExecuteSource, UnityEngine.UI.Button button, Action<Unit> onClick, bool initialValue = true)
  337. {
  338. return ToReactiveCommand(canExecuteSource, initialValue).BindToOnClick(button, onClick);
  339. }
  340. #endif
  341. #endif
  342. }
  343. public static class AsyncReactiveCommandExtensions
  344. {
  345. public static AsyncReactiveCommand ToAsyncReactiveCommand(this IReactiveProperty<bool> sharedCanExecuteSource)
  346. {
  347. return new AsyncReactiveCommand(sharedCanExecuteSource);
  348. }
  349. public static AsyncReactiveCommand<T> ToAsyncReactiveCommand<T>(this IReactiveProperty<bool> sharedCanExecuteSource)
  350. {
  351. return new AsyncReactiveCommand<T>(sharedCanExecuteSource);
  352. }
  353. #if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
  354. static readonly Action<object> Callback = CancelCallback;
  355. static void CancelCallback(object state)
  356. {
  357. var tuple = (Tuple<ICancellableTaskCompletionSource, IDisposable>)state;
  358. tuple.Item2.Dispose();
  359. tuple.Item1.TrySetCanceled();
  360. }
  361. public static Task<T> WaitUntilExecuteAsync<T>(this IAsyncReactiveCommand<T> source, CancellationToken cancellationToken = default(CancellationToken))
  362. {
  363. var tcs = new CancellableTaskCompletionSource<T>();
  364. var subscription = source.Subscribe(x => { tcs.TrySetResult(x); return Observable.ReturnUnit(); });
  365. cancellationToken.Register(Callback, Tuple.Create(tcs, subscription), false);
  366. return tcs.Task;
  367. }
  368. public static System.Runtime.CompilerServices.TaskAwaiter<T> GetAwaiter<T>(this IAsyncReactiveCommand<T> command)
  369. {
  370. return command.WaitUntilExecuteAsync(CancellationToken.None).GetAwaiter();
  371. }
  372. #endif
  373. #if !UniRxLibrary
  374. // for uGUI(from 4.6)
  375. #if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5)
  376. /// <summary>
  377. /// Bind AsyncRaectiveCommand to button's interactable and onClick.
  378. /// </summary>
  379. public static IDisposable BindTo(this IAsyncReactiveCommand<Unit> command, UnityEngine.UI.Button button)
  380. {
  381. var d1 = command.CanExecute.SubscribeToInteractable(button);
  382. var d2 = button.OnClickAsObservable().SubscribeWithState(command, (x, c) => c.Execute(x));
  383. return StableCompositeDisposable.Create(d1, d2);
  384. }
  385. /// <summary>
  386. /// Bind AsyncRaectiveCommand to button's interactable and onClick and register async action to command.
  387. /// </summary>
  388. public static IDisposable BindToOnClick(this IAsyncReactiveCommand<Unit> command, UnityEngine.UI.Button button, Func<Unit, IObservable<Unit>> asyncOnClick)
  389. {
  390. var d1 = command.CanExecute.SubscribeToInteractable(button);
  391. var d2 = button.OnClickAsObservable().SubscribeWithState(command, (x, c) => c.Execute(x));
  392. var d3 = command.Subscribe(asyncOnClick);
  393. return StableCompositeDisposable.Create(d1, d2, d3);
  394. }
  395. /// <summary>
  396. /// Create AsyncReactiveCommand and bind to button's interactable and onClick and register async action to command.
  397. /// </summary>
  398. public static IDisposable BindToOnClick(this UnityEngine.UI.Button button, Func<Unit, IObservable<Unit>> asyncOnClick)
  399. {
  400. return new AsyncReactiveCommand().BindToOnClick(button, asyncOnClick);
  401. }
  402. /// <summary>
  403. /// Create AsyncReactiveCommand and bind sharedCanExecuteSource source to button's interactable and onClick and register async action to command.
  404. /// </summary>
  405. public static IDisposable BindToOnClick(this UnityEngine.UI.Button button, IReactiveProperty<bool> sharedCanExecuteSource, Func<Unit, IObservable<Unit>> asyncOnClick)
  406. {
  407. return sharedCanExecuteSource.ToAsyncReactiveCommand().BindToOnClick(button, asyncOnClick);
  408. }
  409. #endif
  410. #endif
  411. }
  412. }