FIRInstallationsSingleOperationPromiseCache.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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(atomic, 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. if (!self.pendingPromise) {
  41. self.pendingPromise = self.newOperationHandler();
  42. self.pendingPromise
  43. .then(^id(id result) {
  44. self.pendingPromise = nil;
  45. return nil;
  46. })
  47. .catch(^void(NSError *error) {
  48. self.pendingPromise = nil;
  49. });
  50. }
  51. return self.pendingPromise;
  52. }
  53. - (nullable FBLPromise *)getExistingPendingPromise {
  54. return self.pendingPromise;
  55. }
  56. @end