OSSTaskCompletionSource.m 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2014, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. #import "OSSTaskCompletionSource.h"
  11. #import "OSSTask.h"
  12. NS_ASSUME_NONNULL_BEGIN
  13. @interface OSSTask (OSSTaskCompletionSource)
  14. - (BOOL)trySetResult:(nullable id)result;
  15. - (BOOL)trySetError:(NSError *)error;
  16. - (BOOL)trySetException:(NSException *)exception;
  17. - (BOOL)trySetCancelled;
  18. @end
  19. @implementation OSSTaskCompletionSource
  20. #pragma mark - Initializer
  21. + (instancetype)taskCompletionSource {
  22. return [[self alloc] init];
  23. }
  24. - (instancetype)init {
  25. self = [super init];
  26. if (!self) return self;
  27. _task = [[OSSTask alloc] init];
  28. return self;
  29. }
  30. #pragma mark - Custom Setters/Getters
  31. - (void)setResult:(nullable id)result {
  32. if (![self.task trySetResult:result]) {
  33. [NSException raise:NSInternalInconsistencyException
  34. format:@"Cannot set the result on a completed task."];
  35. }
  36. }
  37. - (void)setError:(NSError *)error {
  38. if (![self.task trySetError:error]) {
  39. [NSException raise:NSInternalInconsistencyException
  40. format:@"Cannot set the error on a completed task."];
  41. }
  42. }
  43. - (void)setException:(NSException *)exception {
  44. if (![self.task trySetException:exception]) {
  45. [NSException raise:NSInternalInconsistencyException
  46. format:@"Cannot set the exception on a completed task."];
  47. }
  48. }
  49. - (void)cancel {
  50. if (![self.task trySetCancelled]) {
  51. [NSException raise:NSInternalInconsistencyException
  52. format:@"Cannot cancel a completed task."];
  53. }
  54. }
  55. - (BOOL)trySetResult:(nullable id)result {
  56. return [self.task trySetResult:result];
  57. }
  58. - (BOOL)trySetError:(NSError *)error {
  59. return [self.task trySetError:error];
  60. }
  61. - (BOOL)trySetException:(NSException *)exception {
  62. return [self.task trySetException:exception];
  63. }
  64. - (BOOL)trySetCancelled {
  65. return [self.task trySetCancelled];
  66. }
  67. @end
  68. NS_ASSUME_NONNULL_END