FBLPromise.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /**
  2. Copyright 2018 Google Inc. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at:
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #import "FBLPromisePrivate.h"
  14. /** All states a promise can be in. */
  15. typedef NS_ENUM(NSInteger, FBLPromiseState) {
  16. FBLPromiseStatePending = 0,
  17. FBLPromiseStateFulfilled,
  18. FBLPromiseStateRejected,
  19. };
  20. typedef void (^FBLPromiseObserver)(FBLPromiseState state, id __nullable resolution);
  21. static dispatch_queue_t gFBLPromiseDefaultDispatchQueue;
  22. @implementation FBLPromise {
  23. /** Current state of the promise. */
  24. FBLPromiseState _state;
  25. /**
  26. Set of arbitrary objects to keep strongly while the promise is pending.
  27. Becomes nil after the promise has been resolved.
  28. */
  29. NSMutableSet *__nullable _pendingObjects;
  30. /**
  31. Value to fulfill the promise with.
  32. Can be nil if the promise is still pending, was resolved with nil or after it has been rejected.
  33. */
  34. id __nullable _value;
  35. /**
  36. Error to reject the promise with.
  37. Can be nil if the promise is still pending or after it has been fulfilled.
  38. */
  39. NSError *__nullable _error;
  40. /** List of observers to notify when the promise gets resolved. */
  41. NSMutableArray<FBLPromiseObserver> *_observers;
  42. }
  43. + (void)initialize {
  44. if (self == [FBLPromise class]) {
  45. gFBLPromiseDefaultDispatchQueue = dispatch_get_main_queue();
  46. }
  47. }
  48. + (dispatch_queue_t)defaultDispatchQueue {
  49. @synchronized(self) {
  50. return gFBLPromiseDefaultDispatchQueue;
  51. }
  52. }
  53. + (void)setDefaultDispatchQueue:(dispatch_queue_t)queue {
  54. NSParameterAssert(queue);
  55. @synchronized(self) {
  56. gFBLPromiseDefaultDispatchQueue = queue;
  57. }
  58. }
  59. + (instancetype)pendingPromise {
  60. return [[self alloc] initPending];
  61. }
  62. + (instancetype)resolvedWith:(nullable id)resolution {
  63. return [[self alloc] initWithResolution:resolution];
  64. }
  65. - (void)fulfill:(nullable id)value {
  66. if ([value isKindOfClass:[NSError class]]) {
  67. [self reject:(NSError *)value];
  68. } else {
  69. @synchronized(self) {
  70. if (_state == FBLPromiseStatePending) {
  71. _state = FBLPromiseStateFulfilled;
  72. _value = value;
  73. _pendingObjects = nil;
  74. for (FBLPromiseObserver observer in _observers) {
  75. observer(_state, _value);
  76. }
  77. _observers = nil;
  78. dispatch_group_leave(FBLPromise.dispatchGroup);
  79. }
  80. }
  81. }
  82. }
  83. - (void)reject:(NSError *)error {
  84. NSAssert([error isKindOfClass:[NSError class]], @"Invalid error type.");
  85. if (![error isKindOfClass:[NSError class]]) {
  86. // Give up on invalid error type in Release mode.
  87. @throw error; // NOLINT
  88. }
  89. @synchronized(self) {
  90. if (_state == FBLPromiseStatePending) {
  91. _state = FBLPromiseStateRejected;
  92. _error = error;
  93. _pendingObjects = nil;
  94. for (FBLPromiseObserver observer in _observers) {
  95. observer(_state, _error);
  96. }
  97. _observers = nil;
  98. dispatch_group_leave(FBLPromise.dispatchGroup);
  99. }
  100. }
  101. }
  102. #pragma mark - NSObject
  103. - (NSString *)description {
  104. if (self.isFulfilled) {
  105. return [NSString stringWithFormat:@"<%@ %p> Fulfilled: %@", NSStringFromClass([self class]),
  106. self, self.value];
  107. }
  108. if (self.isRejected) {
  109. return [NSString stringWithFormat:@"<%@ %p> Rejected: %@", NSStringFromClass([self class]),
  110. self, self.error];
  111. }
  112. return [NSString stringWithFormat:@"<%@ %p> Pending", NSStringFromClass([self class]), self];
  113. }
  114. #pragma mark - Private
  115. - (instancetype)initPending {
  116. self = [super init];
  117. if (self) {
  118. dispatch_group_enter(FBLPromise.dispatchGroup);
  119. }
  120. return self;
  121. }
  122. - (instancetype)initWithResolution:(nullable id)resolution {
  123. self = [super init];
  124. if (self) {
  125. if ([resolution isKindOfClass:[NSError class]]) {
  126. _state = FBLPromiseStateRejected;
  127. _error = (NSError *)resolution;
  128. } else {
  129. _state = FBLPromiseStateFulfilled;
  130. _value = resolution;
  131. }
  132. }
  133. return self;
  134. }
  135. - (void)dealloc {
  136. if (_state == FBLPromiseStatePending) {
  137. dispatch_group_leave(FBLPromise.dispatchGroup);
  138. }
  139. }
  140. - (BOOL)isPending {
  141. @synchronized(self) {
  142. return _state == FBLPromiseStatePending;
  143. }
  144. }
  145. - (BOOL)isFulfilled {
  146. @synchronized(self) {
  147. return _state == FBLPromiseStateFulfilled;
  148. }
  149. }
  150. - (BOOL)isRejected {
  151. @synchronized(self) {
  152. return _state == FBLPromiseStateRejected;
  153. }
  154. }
  155. - (nullable id)value {
  156. @synchronized(self) {
  157. return _value;
  158. }
  159. }
  160. - (NSError *__nullable)error {
  161. @synchronized(self) {
  162. return _error;
  163. }
  164. }
  165. - (void)addPendingObject:(id)object {
  166. NSParameterAssert(object);
  167. @synchronized(self) {
  168. if (_state == FBLPromiseStatePending) {
  169. if (!_pendingObjects) {
  170. _pendingObjects = [[NSMutableSet alloc] init];
  171. }
  172. [_pendingObjects addObject:object];
  173. }
  174. }
  175. }
  176. - (void)observeOnQueue:(dispatch_queue_t)queue
  177. fulfill:(FBLPromiseOnFulfillBlock)onFulfill
  178. reject:(FBLPromiseOnRejectBlock)onReject {
  179. NSParameterAssert(queue);
  180. NSParameterAssert(onFulfill);
  181. NSParameterAssert(onReject);
  182. @synchronized(self) {
  183. switch (_state) {
  184. case FBLPromiseStatePending: {
  185. if (!_observers) {
  186. _observers = [[NSMutableArray alloc] init];
  187. }
  188. [_observers addObject:^(FBLPromiseState state, id __nullable resolution) {
  189. dispatch_group_async(FBLPromise.dispatchGroup, queue, ^{
  190. switch (state) {
  191. case FBLPromiseStatePending:
  192. break;
  193. case FBLPromiseStateFulfilled:
  194. onFulfill(resolution);
  195. break;
  196. case FBLPromiseStateRejected:
  197. onReject(resolution);
  198. break;
  199. }
  200. });
  201. }];
  202. break;
  203. }
  204. case FBLPromiseStateFulfilled: {
  205. dispatch_group_async(FBLPromise.dispatchGroup, queue, ^{
  206. onFulfill(self->_value);
  207. });
  208. break;
  209. }
  210. case FBLPromiseStateRejected: {
  211. dispatch_group_async(FBLPromise.dispatchGroup, queue, ^{
  212. onReject(self->_error);
  213. });
  214. break;
  215. }
  216. }
  217. }
  218. }
  219. - (FBLPromise *)chainOnQueue:(dispatch_queue_t)queue
  220. chainedFulfill:(FBLPromiseChainedFulfillBlock)chainedFulfill
  221. chainedReject:(FBLPromiseChainedRejectBlock)chainedReject {
  222. NSParameterAssert(queue);
  223. FBLPromise *promise = [[FBLPromise alloc] initPending];
  224. __auto_type resolver = ^(id __nullable value) {
  225. if ([value isKindOfClass:[FBLPromise class]]) {
  226. [(FBLPromise *)value observeOnQueue:queue
  227. fulfill:^(id __nullable value) {
  228. [promise fulfill:value];
  229. }
  230. reject:^(NSError *error) {
  231. [promise reject:error];
  232. }];
  233. } else {
  234. [promise fulfill:value];
  235. }
  236. };
  237. [self observeOnQueue:queue
  238. fulfill:^(id __nullable value) {
  239. value = chainedFulfill ? chainedFulfill(value) : value;
  240. resolver(value);
  241. }
  242. reject:^(NSError *error) {
  243. id value = chainedReject ? chainedReject(error) : error;
  244. resolver(value);
  245. }];
  246. return promise;
  247. }
  248. @end
  249. @implementation FBLPromise (DotSyntaxAdditions)
  250. + (instancetype (^)(void))pending {
  251. return ^(void) {
  252. return [self pendingPromise];
  253. };
  254. }
  255. + (instancetype (^)(id __nullable))resolved {
  256. return ^(id resolution) {
  257. return [self resolvedWith:resolution];
  258. };
  259. }
  260. @end