我应该在 DAO 中使用什么方法来使用 Room 操作数据库中的数据?
What approach should I use in the DAO to manipulate data in a database using Room?
现在我在我的 DAO 中使用这段代码:
@Dao
interface NotesDao {
@Query("SELECT * FROM Notes")
fun getAllNotes(): List<Notes?>?
@Query("SELECT * FROM Notes WHERE not hidden AND not grouped")
fun getNotes(): List<Notes?>?
@Query("SELECT * FROM Notes WHERE id = :id")
fun getById(id: Long): Notes?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(notes: Notes?)
@Update
fun update(notes: Notes?)
@Delete
fun delete(notes: Notes?)
}
但在许多教程中,我要么看到 Flowable<List<Notes>>
而不是 List<Notes>
或 LiveData<List<Notes>>
。
哪种方法更可取?
您应该考虑两个因素:
- 与数据库的所有交互(查询和更新)都应该在主线程之外。
- 在某些 use-cases 中,您需要单个“one-shot”查询,在其他情况下 - 您希望查询“实时”进行 - 即 return 在数据更改时更新结果(观察者模式)。
使用 Kotlin 您有两个主要选择(哪个更好是个人喜好问题。在一些教程中,您还可以看到用于关闭主线程的 AsyncTask 或 Thread 执行器):
- 使用 RxJava(使用 Flowable 用于“实时”查询,Single - 用于“one-shot”查询和其中之一Single/Completable/Maybe 对应 insert/update/delete)。使用 RxJava,您可以使用 built-in 机制来关闭主线程。
- 为 insert/update/delete 使用协程(和关键字
suspend
),LiveData 或 Flow(来自协程库)用于“实时”查询,或 suspend
- 用于“one-shot”查询。 suspend
让我们从主线程切换。如果您使用 LiveData/Flow,则不需要 suspend
,因为 Room 会自行完成。
另请参阅 official documentation 以获取更多提示。
现在我在我的 DAO 中使用这段代码:
@Dao
interface NotesDao {
@Query("SELECT * FROM Notes")
fun getAllNotes(): List<Notes?>?
@Query("SELECT * FROM Notes WHERE not hidden AND not grouped")
fun getNotes(): List<Notes?>?
@Query("SELECT * FROM Notes WHERE id = :id")
fun getById(id: Long): Notes?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(notes: Notes?)
@Update
fun update(notes: Notes?)
@Delete
fun delete(notes: Notes?)
}
但在许多教程中,我要么看到 Flowable<List<Notes>>
而不是 List<Notes>
或 LiveData<List<Notes>>
。
哪种方法更可取?
您应该考虑两个因素:
- 与数据库的所有交互(查询和更新)都应该在主线程之外。
- 在某些 use-cases 中,您需要单个“one-shot”查询,在其他情况下 - 您希望查询“实时”进行 - 即 return 在数据更改时更新结果(观察者模式)。
使用 Kotlin 您有两个主要选择(哪个更好是个人喜好问题。在一些教程中,您还可以看到用于关闭主线程的 AsyncTask 或 Thread 执行器):
- 使用 RxJava(使用 Flowable 用于“实时”查询,Single - 用于“one-shot”查询和其中之一Single/Completable/Maybe 对应 insert/update/delete)。使用 RxJava,您可以使用 built-in 机制来关闭主线程。
- 为 insert/update/delete 使用协程(和关键字
suspend
),LiveData 或 Flow(来自协程库)用于“实时”查询,或suspend
- 用于“one-shot”查询。suspend
让我们从主线程切换。如果您使用 LiveData/Flow,则不需要suspend
,因为 Room 会自行完成。
另请参阅 official documentation 以获取更多提示。