1 #pragma once
2 
3 #include <jsi/jsi.h>
4 #include <memory>
5 #include "ErrorHandler.h"
6 #include "JSIStoreValueUser.h"
7 #include "RuntimeDecorator.h"
8 #include "Scheduler.h"
9 #include "ShareableValue.h"
10 #include "WorkletsCache.h"
11 
12 namespace reanimated {
13 
14 using namespace facebook;
15 
16 /**
17  A class that manages a jsi::Runtime apart from the React-JS runtime.
18  */
19 class RuntimeManager {
20  public:
21   RuntimeManager(
22       std::shared_ptr<jsi::Runtime> runtime,
23       std::shared_ptr<ErrorHandler> errorHandler,
24       std::shared_ptr<Scheduler> scheduler,
25       RuntimeType runtimeType = RuntimeType::Worklet)
runtime(runtime)26       : runtime(runtime),
27         errorHandler(errorHandler),
28         scheduler(scheduler),
29         workletsCache(std::make_unique<WorkletsCache>()),
30         storeUserData(std::make_shared<StaticStoreUser>()) {
31     RuntimeDecorator::registerRuntime(this->runtime.get(), runtimeType);
32   }
33 
~RuntimeManager()34   virtual ~RuntimeManager() {
35     clearStore();
36   }
37 
38  public:
39   /**
40    Holds the jsi::Function worklet that is responsible for updating values in
41    JS. Can be null.
42    */
43   std::shared_ptr<ShareableValue> valueSetter;
44   /**
45    Holds the jsi::Runtime this RuntimeManager is managing.
46    */
47   std::shared_ptr<jsi::Runtime> runtime;
48   /**
49    Holds the error handler that will be invoked when any kind of error occurs.
50    */
51   std::shared_ptr<ErrorHandler> errorHandler;
52   /**
53    Holds the Scheduler that is responsible for scheduling work on the UI- or
54    React-JS Thread.
55    */
56   std::shared_ptr<Scheduler> scheduler;
57   /**
58    Holds a list of adapted Worklets which are cached to avoid unneccessary
59    recreation.
60    */
61   std::unique_ptr<WorkletsCache> workletsCache;
62   /**
63    Holds the JSI-Value Store where JSI::Values are cached on a
64    per-RuntimeManager basis.
65    */
66   std::shared_ptr<StaticStoreUser> storeUserData;
67 
68  private:
clearStore()69   void clearStore() {
70     const std::lock_guard<std::recursive_mutex> lock(storeUserData->storeMutex);
71     storeUserData->store.clear();
72   }
73 };
74 
75 } // namespace reanimated
76