MainRunLoopEventBeat.mm 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "MainRunLoopEventBeat.h"
  8. #import <React/RCTUtils.h>
  9. #import <mutex>
  10. namespace facebook {
  11. namespace react {
  12. MainRunLoopEventBeat::MainRunLoopEventBeat(EventBeat::SharedOwnerBox const &ownerBox, RuntimeExecutor runtimeExecutor)
  13. : EventBeat(ownerBox), runtimeExecutor_(std::move(runtimeExecutor))
  14. {
  15. mainRunLoopObserver_ = CFRunLoopObserverCreateWithHandler(
  16. NULL /* allocator */,
  17. kCFRunLoopBeforeWaiting /* activities */,
  18. true /* repeats */,
  19. 0 /* order */,
  20. ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
  21. if (!this->isRequested_) {
  22. return;
  23. }
  24. this->lockExecutorAndBeat();
  25. });
  26. assert(mainRunLoopObserver_);
  27. CFRunLoopAddObserver(CFRunLoopGetMain(), mainRunLoopObserver_, kCFRunLoopCommonModes);
  28. }
  29. MainRunLoopEventBeat::~MainRunLoopEventBeat()
  30. {
  31. CFRunLoopRemoveObserver(CFRunLoopGetMain(), mainRunLoopObserver_, kCFRunLoopCommonModes);
  32. CFRelease(mainRunLoopObserver_);
  33. }
  34. void MainRunLoopEventBeat::induce() const
  35. {
  36. if (!this->isRequested_) {
  37. return;
  38. }
  39. RCTExecuteOnMainQueue(^{
  40. this->lockExecutorAndBeat();
  41. });
  42. }
  43. void MainRunLoopEventBeat::lockExecutorAndBeat() const
  44. {
  45. auto owner = ownerBox_->owner.lock();
  46. if (!owner) {
  47. return;
  48. }
  49. executeSynchronouslyOnSameThread_CAN_DEADLOCK(runtimeExecutor_, [this](jsi::Runtime &runtime) { beat(runtime); });
  50. }
  51. } // namespace react
  52. } // namespace facebook