FBLPromise+Timeout.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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+Timeout.h"
  14. #import "FBLPromisePrivate.h"
  15. @implementation FBLPromise (TimeoutAdditions)
  16. - (FBLPromise *)timeout:(NSTimeInterval)interval {
  17. return [self onQueue:FBLPromise.defaultDispatchQueue timeout:interval];
  18. }
  19. - (FBLPromise *)onQueue:(dispatch_queue_t)queue timeout:(NSTimeInterval)interval {
  20. NSParameterAssert(queue);
  21. FBLPromise *promise = [[FBLPromise alloc] initPending];
  22. [self observeOnQueue:queue
  23. fulfill:^(id __nullable value) {
  24. [promise fulfill:value];
  25. }
  26. reject:^(NSError *error) {
  27. [promise reject:error];
  28. }];
  29. typeof(self) __weak weakPromise = promise;
  30. dispatch_after(dispatch_time(0, (int64_t)(interval * NSEC_PER_SEC)), queue, ^{
  31. NSError *timedOutError = [[NSError alloc] initWithDomain:FBLPromiseErrorDomain
  32. code:FBLPromiseErrorCodeTimedOut
  33. userInfo:nil];
  34. [weakPromise reject:timedOutError];
  35. });
  36. return promise;
  37. }
  38. @end
  39. @implementation FBLPromise (DotSyntax_TimeoutAdditions)
  40. - (FBLPromise* (^)(NSTimeInterval))timeout {
  41. return ^(NSTimeInterval interval) {
  42. return [self timeout:interval];
  43. };
  44. }
  45. - (FBLPromise* (^)(dispatch_queue_t, NSTimeInterval))timeoutOn {
  46. return ^(dispatch_queue_t queue, NSTimeInterval interval) {
  47. return [self onQueue:queue timeout:interval];
  48. };
  49. }
  50. @end