FIRInstallationsSingleOperationPromiseCache.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FIRInstallationsSingleOperationPromiseCache.h"
  17. #if __has_include(<FBLPromises/FBLPromises.h>)
  18. #import <FBLPromises/FBLPromises.h>
  19. #else
  20. #import "FBLPromises.h"
  21. #endif
  22. @interface FIRInstallationsSingleOperationPromiseCache <ResultType>()
  23. @property(nonatomic, readonly) FBLPromise *_Nonnull (^newOperationHandler)(void);
  24. @property(nonatomic, nullable) FBLPromise *pendingPromise;
  25. @end
  26. @implementation FIRInstallationsSingleOperationPromiseCache
  27. - (instancetype)initWithNewOperationHandler:
  28. (FBLPromise<id> *_Nonnull (^)(void))newOperationHandler {
  29. if (newOperationHandler == nil) {
  30. [NSException raise:NSInvalidArgumentException
  31. format:@"`newOperationHandler` must not be `nil`."];
  32. }
  33. self = [super init];
  34. if (self) {
  35. _newOperationHandler = [newOperationHandler copy];
  36. }
  37. return self;
  38. }
  39. - (FBLPromise *)getExistingPendingOrCreateNewPromise {
  40. @synchronized(self) {
  41. if (!self.pendingPromise) {
  42. self.pendingPromise = self.newOperationHandler();
  43. self.pendingPromise
  44. .then(^id(id result) {
  45. @synchronized(self) {
  46. self.pendingPromise = nil;
  47. return nil;
  48. }
  49. })
  50. .catch(^void(NSError *error) {
  51. @synchronized(self) {
  52. self.pendingPromise = nil;
  53. }
  54. });
  55. }
  56. return self.pendingPromise;
  57. }
  58. }
  59. - (nullable FBLPromise *)getExistingPendingPromise {
  60. @synchronized(self) {
  61. return self.pendingPromise;
  62. }
  63. }
  64. @end