Future.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // Based on https://github.com/nickgravelyn/UnityToolbag/blob/master/Future/Future.cs
  2. /*
  3. * The MIT License (MIT)
  4. Copyright (c) 2017, Nick Gravelyn
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. * */
  21. using System;
  22. using System.Collections.Generic;
  23. namespace BestHTTP.Futures
  24. {
  25. /// <summary>
  26. /// Describes the state of a future.
  27. /// </summary>
  28. public enum FutureState
  29. {
  30. /// <summary>
  31. /// The future hasn't begun to resolve a value.
  32. /// </summary>
  33. Pending,
  34. /// <summary>
  35. /// The future is working on resolving a value.
  36. /// </summary>
  37. Processing,
  38. /// <summary>
  39. /// The future has a value ready.
  40. /// </summary>
  41. Success,
  42. /// <summary>
  43. /// The future failed to resolve a value.
  44. /// </summary>
  45. Error
  46. }
  47. /// <summary>
  48. /// Defines the interface of an object that can be used to track a future value.
  49. /// </summary>
  50. /// <typeparam name="T">The type of object being retrieved.</typeparam>
  51. public interface IFuture<T>
  52. {
  53. /// <summary>
  54. /// Gets the state of the future.
  55. /// </summary>
  56. FutureState state { get; }
  57. /// <summary>
  58. /// Gets the value if the State is Success.
  59. /// </summary>
  60. T value { get; }
  61. /// <summary>
  62. /// Gets the failure exception if the State is Error.
  63. /// </summary>
  64. Exception error { get; }
  65. /// <summary>
  66. /// Adds a new callback to invoke when an intermediate result is known.
  67. /// </summary>
  68. /// <param name="callback">The callback to invoke.</param>
  69. /// <returns>The future so additional calls can be chained together.</returns>
  70. IFuture<T> OnItem(FutureValueCallback<T> callback);
  71. /// <summary>
  72. /// Adds a new callback to invoke if the future value is retrieved successfully.
  73. /// </summary>
  74. /// <param name="callback">The callback to invoke.</param>
  75. /// <returns>The future so additional calls can be chained together.</returns>
  76. IFuture<T> OnSuccess(FutureValueCallback<T> callback);
  77. /// <summary>
  78. /// Adds a new callback to invoke if the future has an error.
  79. /// </summary>
  80. /// <param name="callback">The callback to invoke.</param>
  81. /// <returns>The future so additional calls can be chained together.</returns>
  82. IFuture<T> OnError(FutureErrorCallback callback);
  83. /// <summary>
  84. /// Adds a new callback to invoke if the future value is retrieved successfully or has an error.
  85. /// </summary>
  86. /// <param name="callback">The callback to invoke.</param>
  87. /// <returns>The future so additional calls can be chained together.</returns>
  88. IFuture<T> OnComplete(FutureCallback<T> callback);
  89. }
  90. /// <summary>
  91. /// Defines the signature for callbacks used by the future.
  92. /// </summary>
  93. /// <param name="future">The future.</param>
  94. public delegate void FutureCallback<T>(IFuture<T> future);
  95. public delegate void FutureValueCallback<T>(T value);
  96. public delegate void FutureErrorCallback(Exception error);
  97. /// <summary>
  98. /// An implementation of <see cref="IFuture{T}"/> that can be used internally by methods that return futures.
  99. /// </summary>
  100. /// <remarks>
  101. /// Methods should always return the <see cref="IFuture{T}"/> interface when calling code requests a future.
  102. /// This class is intended to be constructed internally in the method to provide a simple implementation of
  103. /// the interface. By returning the interface instead of the class it ensures the implementation can change
  104. /// later on if requirements change, without affecting the calling code.
  105. /// </remarks>
  106. /// <typeparam name="T">The type of object being retrieved.</typeparam>
  107. public class Future<T> : IFuture<T>
  108. {
  109. private volatile FutureState _state;
  110. private T _value;
  111. private Exception _error;
  112. private Func<T> _processFunc;
  113. private readonly List<FutureValueCallback<T>> _itemCallbacks = new List<FutureValueCallback<T>>();
  114. private readonly List<FutureValueCallback<T>> _successCallbacks = new List<FutureValueCallback<T>>();
  115. private readonly List<FutureErrorCallback> _errorCallbacks = new List<FutureErrorCallback>();
  116. private readonly List<FutureCallback<T>> _complationCallbacks = new List<FutureCallback<T>>();
  117. /// <summary>
  118. /// Gets the state of the future.
  119. /// </summary>
  120. public FutureState state { get { return _state; } }
  121. /// <summary>
  122. /// Gets the value if the State is Success.
  123. /// </summary>
  124. public T value
  125. {
  126. get
  127. {
  128. if (_state != FutureState.Success && _state != FutureState.Processing)
  129. {
  130. throw new InvalidOperationException("value is not available unless state is Success or Processing.");
  131. }
  132. return _value;
  133. }
  134. }
  135. /// <summary>
  136. /// Gets the failure exception if the State is Error.
  137. /// </summary>
  138. public Exception error
  139. {
  140. get
  141. {
  142. if (_state != FutureState.Error)
  143. {
  144. throw new InvalidOperationException("error is not available unless state is Error.");
  145. }
  146. return _error;
  147. }
  148. }
  149. /// <summary>
  150. /// Initializes a new instance of the <see cref="Future{T}"/> class.
  151. /// </summary>
  152. public Future()
  153. {
  154. _state = FutureState.Pending;
  155. }
  156. public IFuture<T> OnItem(FutureValueCallback<T> callback)
  157. {
  158. if (_state < FutureState.Success && !_itemCallbacks.Contains(callback))
  159. _itemCallbacks.Add(callback);
  160. return this;
  161. }
  162. /// <summary>
  163. /// Adds a new callback to invoke if the future value is retrieved successfully.
  164. /// </summary>
  165. /// <param name="callback">The callback to invoke.</param>
  166. /// <returns>The future so additional calls can be chained together.</returns>
  167. public IFuture<T> OnSuccess(FutureValueCallback<T> callback)
  168. {
  169. if (_state == FutureState.Success)
  170. {
  171. callback(this.value);
  172. }
  173. else if (_state != FutureState.Error && !_successCallbacks.Contains(callback))
  174. {
  175. _successCallbacks.Add(callback);
  176. }
  177. return this;
  178. }
  179. /// <summary>
  180. /// Adds a new callback to invoke if the future has an error.
  181. /// </summary>
  182. /// <param name="callback">The callback to invoke.</param>
  183. /// <returns>The future so additional calls can be chained together.</returns>
  184. public IFuture<T> OnError(FutureErrorCallback callback)
  185. {
  186. if (_state == FutureState.Error)
  187. {
  188. callback(this.error);
  189. }
  190. else if (_state != FutureState.Success && !_errorCallbacks.Contains(callback))
  191. {
  192. _errorCallbacks.Add(callback);
  193. }
  194. return this;
  195. }
  196. /// <summary>
  197. /// Adds a new callback to invoke if the future value is retrieved successfully or has an error.
  198. /// </summary>
  199. /// <param name="callback">The callback to invoke.</param>
  200. /// <returns>The future so additional calls can be chained together.</returns>
  201. public IFuture<T> OnComplete(FutureCallback<T> callback)
  202. {
  203. if (_state == FutureState.Success || _state == FutureState.Error)
  204. {
  205. callback(this);
  206. }
  207. else
  208. {
  209. if (!_complationCallbacks.Contains(callback))
  210. _complationCallbacks.Add(callback);
  211. }
  212. return this;
  213. }
  214. /// <summary>
  215. /// Begins running a given function on a background thread to resolve the future's value, as long
  216. /// as it is still in the Pending state.
  217. /// </summary>
  218. /// <param name="func">The function that will retrieve the desired value.</param>
  219. public IFuture<T> Process(Func<T> func)
  220. {
  221. if (_state != FutureState.Pending)
  222. {
  223. throw new InvalidOperationException("Cannot process a future that isn't in the Pending state.");
  224. }
  225. BeginProcess();
  226. _processFunc = func;
  227. #if NETFX_CORE
  228. #pragma warning disable 4014
  229. Windows.System.Threading.ThreadPool.RunAsync(ThreadFunc);
  230. #pragma warning restore 4014
  231. #else
  232. System.Threading.ThreadPool.QueueUserWorkItem(ThreadFunc);
  233. #endif
  234. return this;
  235. }
  236. private
  237. #if NETFX_CORE
  238. async
  239. #endif
  240. void ThreadFunc(object param)
  241. {
  242. try
  243. {
  244. // Directly call the Impl version to avoid the state validation of the public method
  245. AssignImpl(_processFunc());
  246. }
  247. catch (Exception e)
  248. {
  249. // Directly call the Impl version to avoid the state validation of the public method
  250. FailImpl(e);
  251. }
  252. finally
  253. {
  254. _processFunc = null;
  255. }
  256. }
  257. /// <summary>
  258. /// Allows manually assigning a value to a future, as long as it is still in the pending state.
  259. /// </summary>
  260. /// <remarks>
  261. /// There are times where you may not need to do background processing for a value. For example,
  262. /// you may have a cache of values and can just hand one out. In those cases you still want to
  263. /// return a future for the method signature, but can just call this method to fill in the future.
  264. /// </remarks>
  265. /// <param name="value">The value to assign the future.</param>
  266. public void Assign(T value)
  267. {
  268. if (_state != FutureState.Pending && _state != FutureState.Processing)
  269. {
  270. throw new InvalidOperationException("Cannot assign a value to a future that isn't in the Pending or Processing state.");
  271. }
  272. AssignImpl(value);
  273. }
  274. public void BeginProcess(T initialItem = default(T))
  275. {
  276. _state = FutureState.Processing;
  277. _value = initialItem;
  278. }
  279. public void AssignItem(T value)
  280. {
  281. _value = value;
  282. _error = null;
  283. foreach (var callback in _itemCallbacks)
  284. callback(this.value);
  285. }
  286. /// <summary>
  287. /// Allows manually failing a future, as long as it is still in the pending state.
  288. /// </summary>
  289. /// <remarks>
  290. /// As with the Assign method, there are times where you may know a future value is a failure without
  291. /// doing any background work. In those cases you can simply fail the future manually and return it.
  292. /// </remarks>
  293. /// <param name="error">The exception to use to fail the future.</param>
  294. public void Fail(Exception error)
  295. {
  296. if (_state != FutureState.Pending && _state != FutureState.Processing)
  297. {
  298. throw new InvalidOperationException("Cannot fail future that isn't in the Pending or Processing state.");
  299. }
  300. FailImpl(error);
  301. }
  302. private void AssignImpl(T value)
  303. {
  304. _value = value;
  305. _error = null;
  306. _state = FutureState.Success;
  307. FlushSuccessCallbacks();
  308. }
  309. private void FailImpl(Exception error)
  310. {
  311. _value = default(T);
  312. _error = error;
  313. _state = FutureState.Error;
  314. FlushErrorCallbacks();
  315. }
  316. private void FlushSuccessCallbacks()
  317. {
  318. foreach (var callback in _successCallbacks)
  319. callback(this.value);
  320. FlushComplationCallbacks();
  321. }
  322. private void FlushErrorCallbacks()
  323. {
  324. foreach (var callback in _errorCallbacks)
  325. callback(this.error);
  326. FlushComplationCallbacks();
  327. }
  328. private void FlushComplationCallbacks()
  329. {
  330. foreach (var callback in _complationCallbacks)
  331. callback(this);
  332. ClearCallbacks();
  333. }
  334. private void ClearCallbacks()
  335. {
  336. _itemCallbacks.Clear();
  337. _successCallbacks.Clear();
  338. _errorCallbacks.Clear();
  339. _complationCallbacks.Clear();
  340. }
  341. }
  342. }