From a80e3d1ba6ccede387c84f0eb5afa38085d9e7e1 Mon Sep 17 00:00:00 2001 From: lvmeng <848755140@qq.com> Date: Thu, 12 Mar 2026 17:25:36 +0800 Subject: [PATCH] =?UTF-8?q?ObjectBox=E6=95=B0=E6=8D=AE=E5=BA=93=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E5=A2=9E=E5=8A=A0=E7=BA=BF=E7=A8=8B=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/sw/dualscreen/objbox/ObjectBox.kt | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/sw/dualscreen/objbox/ObjectBox.kt b/app/src/main/java/com/sw/dualscreen/objbox/ObjectBox.kt index 42454fe..2356681 100644 --- a/app/src/main/java/com/sw/dualscreen/objbox/ObjectBox.kt +++ b/app/src/main/java/com/sw/dualscreen/objbox/ObjectBox.kt @@ -143,6 +143,9 @@ object ObjectBox { } catch (e: Exception) { e.printStackTrace() null + } finally { + // 线程资源清理 + boxStore?.closeThreadResources() } } } @@ -177,16 +180,13 @@ object ObjectBox { getBox()?.all } ?: emptyList() - suspend fun filter(name: String?, isDistinct: Boolean = false) = safeDbOp { - val list = if (isDistinct) { - getBox()?.all?.distinctBy { it.foodName } + suspend fun filter(name: String?) = safeDbOp { + if (!name.isNullOrBlank()) { + getBox()?.query(Food_.foodName.contains(name))?.build()?.find() + ?.distinctBy { it.foodName } } else { - getBox()?.all - } - if (name.isNullOrBlank().not()) { - list?.filter { it.foodName?.contains(name) == true } - } - list + getBox()?.all?.distinctBy { it.foodName } + } ?: emptyList() } ?: emptyList() suspend fun removeAll() = safeDbOp { @@ -194,10 +194,7 @@ object ObjectBox { } suspend fun remove(name: String) = safeDbOp { - getBox()?.run { - val filterIdList = all.filter { it.foodName == name }.map { it.id } - removeByIds(filterIdList) - } + getBox()?.query(Food_.foodName.equal(name))?.build()?.remove() } private val dbMutex = Mutex() // 协程并发锁,保证写入操作原子性 @@ -207,9 +204,7 @@ object ObjectBox { // 检查存储是否可读写(操作数据库前调用) fun isStorageAvailable(context: Context): Boolean { return try { - val state = Environment.getExternalStorageState() - val innerDir = context.filesDir - Environment.MEDIA_MOUNTED == state && innerDir.canRead() && innerDir.canWrite() + context.filesDir.canRead() && context.filesDir.canWrite() } catch (e: Exception) { false }