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 }