RuntimeEventBeat.mm 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #include "RuntimeEventBeat.h"
  8. namespace facebook {
  9. namespace react {
  10. RuntimeEventBeat::RuntimeEventBeat(EventBeat::SharedOwnerBox const &ownerBox, RuntimeExecutor runtimeExecutor)
  11. : EventBeat(ownerBox), runtimeExecutor_(std::move(runtimeExecutor))
  12. {
  13. mainRunLoopObserver_ = CFRunLoopObserverCreateWithHandler(
  14. NULL /* allocator */,
  15. kCFRunLoopBeforeWaiting /* activities */,
  16. true /* repeats */,
  17. 0 /* order */,
  18. ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
  19. // Note: We only `induce` beat here; actual beat will be performed on
  20. // a different thread.
  21. this->induce();
  22. });
  23. assert(mainRunLoopObserver_);
  24. CFRunLoopAddObserver(CFRunLoopGetMain(), mainRunLoopObserver_, kCFRunLoopCommonModes);
  25. }
  26. RuntimeEventBeat::~RuntimeEventBeat()
  27. {
  28. CFRunLoopRemoveObserver(CFRunLoopGetMain(), mainRunLoopObserver_, kCFRunLoopCommonModes);
  29. CFRelease(mainRunLoopObserver_);
  30. }
  31. void RuntimeEventBeat::induce() const
  32. {
  33. if (!isRequested_ || isBusy_) {
  34. return;
  35. }
  36. isBusy_ = true;
  37. runtimeExecutor_([this, ownerBox = ownerBox_](jsi::Runtime &runtime) mutable {
  38. auto owner = ownerBox->owner.lock();
  39. if (!owner) {
  40. return;
  41. }
  42. this->beat(runtime);
  43. isBusy_ = false;
  44. });
  45. }
  46. } // namespace react
  47. } // namespace facebook