You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.1 KiB

5 years ago
  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 "FBLPromise+Race.h"
  14. #import "FBLPromise+Async.h"
  15. #import "FBLPromisePrivate.h"
  16. @implementation FBLPromise (RaceAdditions)
  17. + (instancetype)race:(NSArray *)promises {
  18. return [self onQueue:self.defaultDispatchQueue race:promises];
  19. }
  20. + (instancetype)onQueue:(dispatch_queue_t)queue race:(NSArray *)racePromises {
  21. NSParameterAssert(queue);
  22. NSAssert(racePromises.count > 0, @"No promises to observe");
  23. NSArray *promises = [racePromises copy];
  24. return [FBLPromise onQueue:queue
  25. async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  26. for (id promise in promises) {
  27. if (![promise isKindOfClass:self]) {
  28. fulfill(promise);
  29. return;
  30. }
  31. }
  32. // Subscribe all, but only the first one to resolve will change
  33. // the resulting promise's state.
  34. for (FBLPromise *promise in promises) {
  35. [promise observeOnQueue:queue fulfill:fulfill reject:reject];
  36. }
  37. }];
  38. }
  39. @end
  40. @implementation FBLPromise (DotSyntax_RaceAdditions)
  41. + (FBLPromise * (^)(NSArray *))race {
  42. return ^(NSArray *promises) {
  43. return [self race:promises];
  44. };
  45. }
  46. + (FBLPromise * (^)(dispatch_queue_t, NSArray *))raceOn {
  47. return ^(dispatch_queue_t queue, NSArray *promises) {
  48. return [self onQueue:queue race:promises];
  49. };
  50. }
  51. @end