[TIL] ๐ผ24/05/09๐ผ#Room asynchronous query
Room asynchronous query
๐์ฐธ๊ณ ์๋ฃ
- Room asynchronous query
- asynchronous one-shot write query
- observable query
asynchronous one-shot ์ฟผ๋ฆฌ
- suspend ํค์๋ ์ฌ์ฉ, Room Entity ํด๋์ค ์ธ์คํด์ค ๋ฐํ
- one-shot ์ฟผ๋ฆฌ์ธ ์ด์ ?
ํจ์๋ฅผ ํธ์ถํ์ ๋ ์ํ๋จ, ํจ์ ์ํ๋ ๋์ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ํ ์ค๋
์ท ๋ฐํ
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUsers(vararg users: User)
@Update
suspend fun updateUsers(vararg users: User)
@Delete
suspend fun deleteUsers(vararg users: User)
@Query("SELECT * FROM user WHERE id = :id")
suspend fun loadUserById(id: Int): User
@Query("SELECT * from user WHERE region IN (:regions)")
suspend fun loadUsersByRegion(regions: List<String>): List<User>
}
observable ์ฟผ๋ฆฌ
- suspend ํค์๋ ์ฌ์ฉ X, Flow ๋ฐํ
- Room Entity ํด๋์ค ์ธ์คํด์ค ๋ชฉ๋ก์ ๋ฐํ๋ฐ์ ๋,
Flow<*>
๊ฐ ์๋ Flow<List<*>>
ํ์
์ผ๋ก ๋ฐํ ๋ฐ์!
- observableํ ์ด์ ?
- ์ฟผ๋ฆฌ๊ฐ ์ฐธ์กฐํ๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ๋ณํ๊ฐ ์๊ธฐ๋ฉด, ์ฟผ๋ฆฌ๋ฅผ ์๋์ ์ผ๋ก ์ํํ์ฌ ๊ฒฐ๊ณผ emit
- whenever any row in the table is updated
โ ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๋ก ๋ฐํ๋๋ row์๋ ๋ณํ๊ฐ ์์ ์๋ ์์
โ ๋ณํ๊ฐ ์์ ๋๋ง UI์๊ฒ notify๋๋๋ก distinctUtilChanged
์ฐ์ฐ์ ์ ์ฉํด์ฃผ๊ธฐ
@Dao
interface UserDao {
@Query("SELECT * FROM user WHERE id = :id")
fun loadUserById(id: Int): Flow<User>
@Query("SELECT * from user WHERE region IN (:regions)")
fun loadUsersByRegion(regions: List<String>): Flow<List<User>>
}