主线程上的房间无效方法
Room void methods on main thread
当为 Android 使用 Room 库时,文档明确指出我们不能在主线程上进行调用,除非我们明确允许它们。我很好奇的是具有 void
return 类型的方法。 returning LiveData
会自动 运行 它们离开主线程似乎很愚蠢,但 void 类型不会(除非我遗漏了什么)。有什么简单的方法可以做到这一点,而不必 运行 在我自己的托管线程中这样做吗?
我的查询:
@Dao
interface UserDao {
@Query("DELETE FROM users")
fun clear()
}
我什至尝试过使用 Kotlin 反射 + 扩展函数,但这似乎在 运行 时间失败了:
fun KFunction<Unit>.execOn(executor: Executor, vararg args: Any?) {
executor.execute {
this.call(args)
}
}
然后拨打电话:
myDb.userDao()::clear.execOn(diskExecutor)
注意有效的是:
diskExecutor.execute {
myDb.userDao().clear()
}
It seems silly that returning LiveData will automatically run them off the main thread, but void types will not (unless I'm missing something).
如果没有某种注释,Room 将不知道您希望 void
-returning DAO 方法在后台线程上 运行。对于响应式 return 类型(例如 LiveData
、Single
),您明确请求后台执行,因此不需要额外的元数据(例如注释)。
您可以考虑为这种基于注释的方法提交功能请求。
Is there any easy way I can do this without having to run this in my own managed thread?
如果你问的是"does Room have a background-execution option for DAO methods other than those with reactive return types?",那么答案是否定的,至少目前是这样。
当为 Android 使用 Room 库时,文档明确指出我们不能在主线程上进行调用,除非我们明确允许它们。我很好奇的是具有 void
return 类型的方法。 returning LiveData
会自动 运行 它们离开主线程似乎很愚蠢,但 void 类型不会(除非我遗漏了什么)。有什么简单的方法可以做到这一点,而不必 运行 在我自己的托管线程中这样做吗?
我的查询:
@Dao
interface UserDao {
@Query("DELETE FROM users")
fun clear()
}
我什至尝试过使用 Kotlin 反射 + 扩展函数,但这似乎在 运行 时间失败了:
fun KFunction<Unit>.execOn(executor: Executor, vararg args: Any?) {
executor.execute {
this.call(args)
}
}
然后拨打电话:
myDb.userDao()::clear.execOn(diskExecutor)
注意有效的是:
diskExecutor.execute {
myDb.userDao().clear()
}
It seems silly that returning LiveData will automatically run them off the main thread, but void types will not (unless I'm missing something).
如果没有某种注释,Room 将不知道您希望 void
-returning DAO 方法在后台线程上 运行。对于响应式 return 类型(例如 LiveData
、Single
),您明确请求后台执行,因此不需要额外的元数据(例如注释)。
您可以考虑为这种基于注释的方法提交功能请求。
Is there any easy way I can do this without having to run this in my own managed thread?
如果你问的是"does Room have a background-execution option for DAO methods other than those with reactive return types?",那么答案是否定的,至少目前是这样。