Android Rxjava Room DB

passΒ·2023λ…„ 6μ›” 18일
0

Android

λͺ©λ‘ 보기
13/41

πŸ”₯ Rxjava와 ν•¨κ»˜ Android Room DB κ΅¬ν˜„ν•˜κΈ°

🎈 λ°μ΄ν„°λ² μ΄μŠ€ μ•‘μ„ΈμŠ€μ™€ 같이 무거운 싀행은 MainThread κ°€ μ•„λ‹Œ λ‹€λ₯Έ Threadμ—μ„œ μ‹€ν–‰ν•΄μ•Ό ν•˜λŠ”λ°, 이번 μ˜ˆμ œμ—μ„œλŠ” Rxjava3 λ₯Ό μ μš©μ‹œμΌœμ„œ Room DB λ₯Ό κ΅¬ν˜„ν•˜μ˜€λ‹€.


πŸ“‘ μˆœμ„œ

  1. build.gradle
  2. Dao, μ‚¬μš©



βœ” build.gradle

plugins {
    ...
    id 'kotlin-kapt'
}

dependencies {
	...
    implementation "androidx.room:room-runtime:2.5.1"
    annotationProcessor "androidx.room:room-compiler:2.5.1"
    implementation "androidx.room:room-rxjava3:2.5.1"

    implementation 'io.reactivex.rxjava3:rxandroid:3.0.2'
    implementation 'io.reactivex.rxjava3:rxjava:3.1.5'
}



βœ” Dao

@Dao
public interface TestDao {
    @Query("SELECT * FROM testInfo")
    Single<List<TestInfo>> getAll();

    @Insert
    Completable addTest(TestInfo testInfo);

    @Update
    Completable updateTest(TestInfo testInfo);
}
  • Room DB λŠ” Rxjavaλ₯Ό μ μš©ν•˜κΈ° μ‰½κ²Œ κ΅¬ν˜„λ˜μ–΄ μžˆλ‹€.
  • Daoμ—μ„œ Single, Completable, Flowable 등을 μ„ νƒν•˜μ—¬ μž‘μ„±ν•˜λ©΄, κ°„λ‹¨ν•˜κ²Œ 연동할 수 μžˆλ‹€.
  • μœ„ μ˜ˆμ œμ—μ„œ addTest() 와 updateText() λŠ” 데이터λ₯Ό λ°œν–‰ν•  ν•„μš” 없이 μˆ˜ν–‰λ§Œ μ§„ν–‰ν•˜κ³  μ’…λ£Œμ‹œν‚€κΈ° μœ„ν•˜μ—¬ Completable을 μ‚¬μš©ν•˜μ˜€λ‹€.



βœ” μ‚¬μš©

// μ‚¬μš©
TestDataBase.getInstance(context)
        .testDao()
        .addTest(testInfo)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe();
        
TestDataBase.getInstance(context)
        .testDao()
        .getAll()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSuccess(list -> {
            // 성곡
        }).subscribe();        
  • Rxjava λŠ” subscribe 와 observe λ₯Ό μ‚¬μš©ν•˜μ—¬ νŠΉμ • 이벀트λ₯Ό κ΄€μ°°ν•˜κ³  κ΅¬λ…ν•œλ‹€λŠ” κ°œλ…μ„ μ‚¬μš©ν•œλ‹€.
  • μ΄λ ‡κ²Œ ꡬ독을 ν•˜κ³ , μ΄λ²€νŠΈκ°€ λ°œμƒν•˜μ˜€μ„ λ•Œ, κ΅¬λ…ν•œ μ‚¬μš©μžμ—κ²Œ 데이터가 λ°œν–‰λœλ‹€κ³  λ§ν•œλ‹€.
profile
μ•ˆλ“œλ‘œμ΄λ“œ 개발자 지망생

0개의 λŒ“κΈ€