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 @@ -20,6 +20,24 @@ task(); } + void scheduleOrRunCancellableCommonImpl(const taskType task) { + if (this->tasksCancelled.load()) { + throw std::runtime_error("TASK_CANCELLED"); + return; + } + if (this->databaseThread != nullptr) { + this->databaseThread->scheduleTask([this, task]() { + if (this->tasksCancelled.load()) { + throw std::runtime_error("TASK_CANCELLED"); + } else { + task(); + } + }); + return; + } + task(); + } + void enableMultithreadingCommonImpl() { if (this->databaseThread == nullptr) { this->databaseThread = std::make_unique("database"); @@ -30,6 +48,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->scheduleOrRunCommonImpl(task); + }); +} + void GlobalDBSingleton::enableMultithreading() { if (NSThread.isMainThread) { this->enableMultithreadingCommonImpl();