改造objectbox

This commit is contained in:
2026-01-31 17:49:44 +08:00
parent 4322c9495b
commit af120eabd0
7 changed files with 120 additions and 74 deletions
@@ -47,9 +47,11 @@ object FoodModule {
suspend fun init(context: Context) {
withContext(Dispatchers.IO) {
module_mobile = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
val box = ObjectBox.getBox<Food>()
if (box?.all?.isEmpty() == true) {
initDefFoodData(context)
ObjectBox.safeDbOp {
val box = ObjectBox.getBox<Food>()
if (box?.all?.isEmpty() == true) {
initDefFoodData(context)
}
}
}
}
@@ -174,6 +174,21 @@ object ObjectBox {
getBox<Food>()?.put(entities)
}
suspend fun filter(name:String?) = safeDbOp {
var list = getBox<Food>()?.all?.distinctBy { it.name }
if (name.isNullOrBlank().not()) {
list?.filter { it.name?.contains(name!!) == true }
}
list?:emptyList()
}
suspend fun remove(name:String) = safeDbOp {
getBox<Food>()?.run {
val filterIdList = all.filter { it.name == name }.map { it.id }
removeByIds(filterIdList)
}
}
private val dbMutex = Mutex() // 协程并发锁,保证写入操作原子性
private const val DB_DIR_NAME = "objectbox" // ObjectBox 默认数据库目录
private const val BACKUP_DIR_NAME = "objectbox_backup" // 备份目录