diff --git a/native/android/app/src/cpp/GlobalDBSingleton.cpp b/native/android/app/src/cpp/GlobalDBSingleton.cpp --- a/native/android/app/src/cpp/GlobalDBSingleton.cpp +++ b/native/android/app/src/cpp/GlobalDBSingleton.cpp @@ -14,6 +14,10 @@ this->scheduleOrRunCommonImpl(task); } +void GlobalDBSingleton::scheduleOrRunCancellable(const taskType task) { + this->scheduleOrRunCancellableCommonImpl(task); +} + void GlobalDBSingleton::enableMultithreading() { this->enableMultithreadingCommonImpl(); } diff --git a/native/cpp/CommonCpp/NativeModules/CommCoreModule.cpp b/native/cpp/CommonCpp/NativeModules/CommCoreModule.cpp --- a/native/cpp/CommonCpp/NativeModules/CommCoreModule.cpp +++ b/native/cpp/CommonCpp/NativeModules/CommCoreModule.cpp @@ -19,7 +19,7 @@ jsi::Runtime &rt, std::function task) { std::promise promise; - GlobalDBSingleton::instance.scheduleOrRun([&promise, &task]() { + GlobalDBSingleton::instance.scheduleOrRunCancellable([&promise, &task]() { try { if constexpr (std::is_void::value) { task(); diff --git a/native/cpp/CommonCpp/NativeModules/InternalModules/GlobalDBSingleton.h b/native/cpp/CommonCpp/NativeModules/InternalModules/GlobalDBSingleton.h --- a/native/cpp/CommonCpp/NativeModules/InternalModules/GlobalDBSingleton.h +++ b/native/cpp/CommonCpp/NativeModules/InternalModules/GlobalDBSingleton.h @@ -5,6 +5,9 @@ #include namespace comm { + +const std::string TASK_CANCELLED_FLAG("TASK_CANCELLED"); + class GlobalDBSingleton { std::atomic multithreadingEnabled; std::unique_ptr databaseThread; @@ -20,6 +23,22 @@ task(); } + void scheduleOrRunCancellableCommonImpl(const taskType task) { + if (this->tasksCancelled.load()) { + throw std::runtime_error(TASK_CANCELLED_FLAG); + } + if (this->databaseThread == nullptr) { + task(); + return; + } + this->databaseThread->scheduleTask([this, task]() { + if (this->tasksCancelled.load()) { + throw std::runtime_error(TASK_CANCELLED_FLAG); + } + task(); + }); + } + void enableMultithreadingCommonImpl() { if (this->databaseThread == nullptr) { this->databaseThread = std::make_unique("database"); @@ -30,6 +49,7 @@ public: static GlobalDBSingleton instance; void scheduleOrRun(const taskType task); + void scheduleOrRunCancellable(const taskType task); void enableMultithreading(); void setTasksCancelled(bool tasksCancelled) { this->tasksCancelled.store(tasksCancelled); diff --git a/native/ios/Comm/GlobalDBSingleton.mm b/native/ios/Comm/GlobalDBSingleton.mm --- a/native/ios/Comm/GlobalDBSingleton.mm +++ b/native/ios/Comm/GlobalDBSingleton.mm @@ -21,6 +21,17 @@ }); } +void GlobalDBSingleton::scheduleOrRunCancellable(const taskType task) { + if (NSThread.isMainThread || this->multithreadingEnabled.load()) { + this->scheduleOrRunCancellableCommonImpl(task); + return; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + this->scheduleOrRunCancellableCommonImpl(task); + }); +} + void GlobalDBSingleton::enableMultithreading() { if (NSThread.isMainThread) { this->enableMultithreadingCommonImpl();