[TIL] ๐ŸŒผ24/05/09๐ŸŒผ#Room asynchronous query

0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
97/104
post-thumbnail
post-custom-banner

[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>>
}
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€