使用Kotlin構建MVVM應用程序—第三部分:Room

目錄

寫在前面

這是使用Kotlin構建MVVM應用程序—第三部分:Roomhtml

在上一篇中咱們瞭解了MVVM是怎麼處理網絡數據的,而這一篇則介紹的是如何進行數據持久化。java

Room

Room是google推出的一個數據持久化庫,它是 Architecture Component的一部分。它讓SQLiteDatabase的使用變得簡單,大大減小了重複的代碼,而且把SQL查詢的檢查放在了編譯時。android

Room使用起來很是簡單,並且能夠和RxJava配合使用,和咱們的技術體系十分契合。git

加入依賴

首先在項目的build.gradle中加入github

allprojects {
    repositories {
        maven {
            url 'https://maven.google.com'
        }
        jcenter()
    }
}
複製代碼

接着在app的build.gradle中加入它的依賴sql

//room (local)
implementation 'android.arch.persistence.room:runtime:1.0.0'
implementation 'android.arch.persistence.room:rxjava2:1.0.0'
kapt 'android.arch.persistence.room:compiler:1.0.0'
//facebook出品,可在Chrome中查看數據庫
implementation 'com.facebook.stetho:stetho:1.5.0'
複製代碼

如今的結構數據庫

MVVM

這裏咱們多了一層Repository,使用這一層來確保單一數據源,保證數據來源的惟一和正確性(即不論是來自網絡或是本地緩存的)。ViewModel層並不須要知道它使用到的數據是怎麼來的,就好似開發者並不須要知道設計師是如何畫出UI圖的同樣。api

開始正文緩存

使用Room進行持久化

  1. 新建相應的表

Room爲每一個用@Entity註解了的類建立一張表服務器

@Entity(tableName = "articles")
class Article(var title: String?){

    @PrimaryKey
    @ColumnInfo(name = "articleid")
    var id: Int = 0
    var content: String? = null
    var readme: String? = null
    @SerializedName("describe")
    var description: String? = null
    var click: Int = 0
    var channel: Int = 0
    var comments: Int = 0
    var stow: Int = 0
    var upvote: Int = 0
    var downvote: Int = 0
    var url: String? = null
    var pubDate: String? = null
    var thumbnail: String? = null
}
複製代碼
  1. 建立相關的Dao

至關於Retrofit中的api接口

DAO負責定義操做數據庫的方法。在SQLite實現的版本中,全部的查詢都是在LocalUserDataSource文件中完成的,裏面主要是 使用了Cursor對象來完成查詢的工做。有了Room,咱們再也不須要Cursor的相關代碼,而只需在Dao類中使用註解來定義查詢。

@Dao
interface PaoDao{

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insetAll(articles: List<Article>)

    @Query("SELECT * FROM Articles WHERE articleid= :id")
    fun getArticleById(id:Int):Single<Article>


    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertArticle(article :Article)

}
複製代碼
  1. 建立數據庫

    至關於建立RetrofitClient對象

    咱們須要定義一個繼承了RoomDatabase的抽象類。這個類使用@Database來註解,列出它所包含的Entity以及操做它們的 DAO 。

    @Database(entities = arrayOf(Article::class),version = 1)
    abstract class AppDatabase :RoomDatabase(){
    
        abstract fun paoDao(): PaoDao
    
        companion object {
            @Volatile private var INSTANCE: AppDatabase? = null
            fun getInstance(context: Context): AppDatabase =
                    INSTANCE ?: synchronized(this) {
                        INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
                    }
    
            private fun buildDatabase(context: Context) =
                    Room.databaseBuilder(context.applicationContext,
                            AppDatabase::class.java, "app.db")
                            .build()
        }
    
    }
    複製代碼

Over ,集成Room十分的簡單。

更多關於Room的使用方法,它的遷移,表之間的關聯和字段。

推薦查看泡網的Room專題:Room

實踐

這裏咱們對上一篇中的從服務器端獲取到的Article文章進行持久化。

  1. 修改一下Model層的代碼,添加Repository做爲ViewModel層的數據源
class PaoRepo constructor(private val remote:PaoService,private val local :PaoDao){
	//首先查看本地數據庫是否存在該篇文章
    fun getArticleDetail(id:Int)= local.getArticleById(id)
            .onErrorResumeNext {
              	//本地數據庫不存在,會拋出EmptyResultSetException
              	//轉而獲取網絡數據,成功後保存到數據庫
                remote.getArticleDetail(id)
                        .doOnSuccess { local.insertArticle(it) }
            }
}
複製代碼

咱們的目錄結構會以下圖所示:

結構

  1. 修改咱們的ViewModel層的數據源

在上一篇中咱們使用的是PaoService網絡數據做爲數據源,這裏只須要修改成PaoRepo

class PaoViewModel(private val repo: PaoRepo) 
複製代碼

之後統一使用PaoRepo來爲PaoViewModel提供數據

  1. 在View層中將PaoRepo注入到PaoViewModel
//////model
val remote=Retrofit.Builder()
        .baseUrl(Constants.HOST_API)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build().create(PaoService::class.java)
val local=AppDatabase.getInstance(applicationContext).paoDao()
val repo = PaoRepo(remote, local)
/////ViewModel
mViewMode= PaoViewModel(repo)
////binding
mBinding.vm=mViewMode
複製代碼

看看效果

image

Roomigrant

Roomigrant is a helper library to automatically generate Android Room library migrations using compile-time code generation.

這是一個幫助開發者進行Room數據遷移的庫,使用起來很是方便。

在使用Room的過程當中,或多或少都會遇到增長表、改變表字段的狀況。可是Room的遷移比較麻煩,能夠看看理解Room的數據遷移這篇文章,增長新表還好,只須要修改版本號,可是若是須要修改表字段的話,因爲sqlite的歷史緣由:SQLite的ALTER TABLE命令很是侷限,只支持重命名錶以及添加新的字段。

所以咱們須要:

  • 建立一個新的臨時表,
  • 把users表中的數據拷貝到臨時表中
  • 丟棄users表
  • 把臨時表重命名爲users

使用Room,Migration的實現是這樣的:

static final Migration MIGRATION_3_4 = new Migration(3, 4) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        // Create the new table
        database.execSQL(
                "CREATE TABLE users_new (userid TEXT, username TEXT, last_update INTEGER, PRIMARY KEY(userid))");
// Copy the data
        database.execSQL(
                "INSERT INTO users_new (userid, username, last_update) SELECT userid, username, last_update FROM users");
// Remove the old table
        database.execSQL("DROP TABLE users");
// Change the table name to the correct one
        database.execSQL("ALTER TABLE users_new RENAME TO users");
    }
};
複製代碼

對於開發者還須要編寫大量的sql語句,能夠說是不友好了。

可是幸運的是Roomigrant幫助咱們作到了以上的事,對於修改表字段,只須要簡單的

自定義一個Rule,通知一下什麼表下的哪一個字段須要修改

// version 3 的users表的字段uId
// version 4 相應的字段改成了userId
@FieldMigrationRule(version1 = 3, version2 = 4, table = "users", field = "uId")
fun migrate_3_4_Object1Dbo_intVal(): String {
	return "`users`.`userId`"
}
複製代碼

這樣Roomigrant即可以幫助咱們生成那些模板式的代碼。

寫在最後

本項目的github地址:github.com/ditclear/MV…

更多的例子能夠查看:github.com/ditclear/Pa…

這是使用Kotlin構建MVVM項目的第三部分,主要講了怎麼在MVVM中進行數據的持久化以及爲ViewModel層提供Repository做爲惟一的數據源。

總結一下前三篇的內容即是:

使用Retrofit提供來自服務端的數據,使用Room來進行持久化,而後提供一個Repository來爲ViewModel提供數據,ViewModel層利用RxJava來進行數據的轉換,配合DataBinding引發View層的變化。

邏輯很清晰了,但惟一的遺憾即是爲了提供一個ViewModel咱們須要寫太多模板化的代碼了

//////model
val remote=Retrofit.Builder()
        .baseUrl(Constants.HOST_API)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build().create(PaoService::class.java)
val local=AppDatabase.getInstance(applicationContext).paoDao()
val repo = PaoRepo(remote, local)
/////ViewModel
mViewMode= PaoViewModel(repo)
複製代碼

若是能不寫該多好。

上帝說:能夠。

因此下一篇的內容即是依賴注入—Dagger2,從入門到放棄到恍然大悟到愛不釋手。。。

相關文章
相關標籤/搜索