ObjectBox数据库操作增加线程资源清理

This commit is contained in:
2026-03-12 17:25:36 +08:00
parent 6d825d7235
commit a80e3d1ba6
@@ -143,6 +143,9 @@ object ObjectBox {
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
null null
} finally {
// 线程资源清理
boxStore?.closeThreadResources()
} }
} }
} }
@@ -177,16 +180,13 @@ object ObjectBox {
getBox<Food>()?.all getBox<Food>()?.all
} ?: emptyList() } ?: emptyList()
suspend fun filter(name: String?, isDistinct: Boolean = false) = safeDbOp { suspend fun filter(name: String?) = safeDbOp {
val list = if (isDistinct) { if (!name.isNullOrBlank()) {
getBox<Food>()?.all?.distinctBy { it.foodName } getBox<Food>()?.query(Food_.foodName.contains(name))?.build()?.find()
?.distinctBy { it.foodName }
} else { } else {
getBox<Food>()?.all getBox<Food>()?.all?.distinctBy { it.foodName }
} } ?: emptyList()
if (name.isNullOrBlank().not()) {
list?.filter { it.foodName?.contains(name) == true }
}
list
} ?: emptyList() } ?: emptyList()
suspend fun removeAll() = safeDbOp { suspend fun removeAll() = safeDbOp {
@@ -194,10 +194,7 @@ object ObjectBox {
} }
suspend fun remove(name: String) = safeDbOp { suspend fun remove(name: String) = safeDbOp {
getBox<Food>()?.run { getBox<Food>()?.query(Food_.foodName.equal(name))?.build()?.remove()
val filterIdList = all.filter { it.foodName == name }.map { it.id }
removeByIds(filterIdList)
}
} }
private val dbMutex = Mutex() // 协程并发锁,保证写入操作原子性 private val dbMutex = Mutex() // 协程并发锁,保证写入操作原子性
@@ -207,9 +204,7 @@ object ObjectBox {
// 检查存储是否可读写(操作数据库前调用) // 检查存储是否可读写(操作数据库前调用)
fun isStorageAvailable(context: Context): Boolean { fun isStorageAvailable(context: Context): Boolean {
return try { return try {
val state = Environment.getExternalStorageState() context.filesDir.canRead() && context.filesDir.canWrite()
val innerDir = context.filesDir
Environment.MEDIA_MOUNTED == state && innerDir.canRead() && innerDir.canWrite()
} catch (e: Exception) { } catch (e: Exception) {
false false
} }