FBLPromise+Race.m 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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