FSTDispatchQueue.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright 2017 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 <Foundation/Foundation.h>
  17. #import "Firestore/Source/Util/FSTAssert.h"
  18. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  19. NS_ASSUME_NONNULL_BEGIN
  20. @interface FSTDispatchQueue ()
  21. - (instancetype)initWithQueue:(dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER;
  22. @end
  23. @implementation FSTDispatchQueue
  24. + (instancetype)queueWith:(dispatch_queue_t)dispatchQueue {
  25. return [[FSTDispatchQueue alloc] initWithQueue:dispatchQueue];
  26. }
  27. - (instancetype)initWithQueue:(dispatch_queue_t)queue {
  28. if (self = [super init]) {
  29. _queue = queue;
  30. }
  31. return self;
  32. }
  33. - (void)verifyIsCurrentQueue {
  34. FSTAssert([self onTargetQueue],
  35. @"We are running on the wrong dispatch queue. Expected '%@' Actual: '%@'",
  36. [self targetQueueLabel], [self currentQueueLabel]);
  37. }
  38. - (void)dispatchAsync:(void (^)(void))block {
  39. FSTAssert(![self onTargetQueue],
  40. @"dispatchAsync called when we are already running on target dispatch queue '%@'",
  41. [self targetQueueLabel]);
  42. dispatch_async(self.queue, block);
  43. }
  44. - (void)dispatchAsyncAllowingSameQueue:(void (^)(void))block {
  45. dispatch_async(self.queue, block);
  46. }
  47. - (void)dispatchAfterDelay:(NSTimeInterval)delay block:(void (^)(void))block {
  48. dispatch_time_t delayNs = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
  49. dispatch_after(delayNs, self.queue, block);
  50. }
  51. #pragma mark - Private Methods
  52. - (NSString *)currentQueueLabel {
  53. return [NSString stringWithUTF8String:dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)];
  54. }
  55. - (NSString *)targetQueueLabel {
  56. return [NSString stringWithUTF8String:dispatch_queue_get_label(self.queue)];
  57. }
  58. - (BOOL)onTargetQueue {
  59. return [[self currentQueueLabel] isEqualToString:[self targetQueueLabel]];
  60. }
  61. @end
  62. NS_ASSUME_NONNULL_END