GIDCallbackQueue.m 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2021 Google LLC
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  15. NS_ASSUME_NONNULL_BEGIN
  16. @interface GIDCallbackQueue () {
  17. // Whether we are in the middle of firing callbacks loop.
  18. BOOL _firing;
  19. // Number of currently pending operations.
  20. int _pending; // number of pending operations
  21. // The ordered list of callback blocks.
  22. NSMutableArray *_queue;
  23. // A strong reference back to self to prevent it from being released when
  24. // there is operation pending.
  25. GIDCallbackQueue *_strongSelf;
  26. }
  27. @end
  28. @implementation GIDCallbackQueue
  29. - (id)init {
  30. self = [super init];
  31. if (self) {
  32. _queue = [NSMutableArray new];
  33. }
  34. return self;
  35. }
  36. - (void)wait {
  37. _pending++;
  38. // The queue itself should be retained as long as there are pending
  39. // operations.
  40. _strongSelf = self;
  41. }
  42. - (void)next {
  43. if (!_pending) {
  44. return;
  45. }
  46. _pending--;
  47. if (!_pending) {
  48. // Use an autoreleasing variable to hold self temporarily so it is not
  49. // released while this method is executing.
  50. __autoreleasing GIDCallbackQueue *autoreleasingSelf = self;
  51. _strongSelf = nil;
  52. [autoreleasingSelf fire];
  53. }
  54. }
  55. - (void)reset {
  56. [_queue removeAllObjects];
  57. _pending = 0;
  58. _strongSelf = nil;
  59. }
  60. - (void)addCallback:(GIDCallbackQueueCallback)callback {
  61. if (!callback) {
  62. return;
  63. }
  64. [_queue addObject:[callback copy]];
  65. if (!_pending) {
  66. [self fire];
  67. }
  68. }
  69. // Fires the callbacks.
  70. - (void)fire {
  71. if (_firing) {
  72. return;
  73. }
  74. _firing = YES;
  75. while (!_pending && [_queue count]) {
  76. GIDCallbackQueueCallback callback = [_queue objectAtIndex:0];
  77. [_queue removeObjectAtIndex:0];
  78. callback();
  79. }
  80. _firing = NO;
  81. }
  82. @end
  83. NS_ASSUME_NONNULL_END