MVVM framework construction (a) – background

The construction of MVVM framework (ii) – project construction

The construction of MVVM framework (three) — network request

MVVM data persistence (2) — use of ROOM

MVVM data persistence

We’ve covered the tragedy of the MVVM framework, project building, and network requests. In this article, we’ll talk about MVVM data persistence, also known as caching

Room

The Room persistent library provides an SQLite abstraction layer to make your database access more robust and improve database performance. Introduction to address developer. The android. Google. Cn/training/da… Room provides an abstraction layer on TOP of SQLite to allow smooth database access while leveraging SQLite’s capabilities, most importantly it makes SQLiteDatabase easy to use, greatly reducing repetitive code, and puts the checking of SQL queries at compile time. It also works well with RxJava.

Room has three main components
The Database:

Contains the database holder and acts as the primary access point for the underlying connection to the application’s persistent, relational data. A class annotated with @Database should satisfy the following criteria: It is an abstract class that inherits RoomDatabase. Include a list of entities associated with the database in the annotation. Contains an abstract method with zero arguments and returns a class annotated with @DAO. At runtime, you can call Room. DatabaseBuilder () or Room. InMemoryDatabaseBuilder () for the database instance.

The Entity:

Represents a table within a database.

DAO:

Contains methods to access the database.

And a diagram of the relationship between the three:

Join the rely on

So with that brief introduction to Room we’re going to focus on how to use it in our framework first add dependencies, okay

    implementation 'android. Arch. Persistence. Room: the runtime: 1.1.1'
    implementation 'android. Arch. Persistence. Room: rxjava2:1.1.1'
    kapt 'android. Arch. Persistence. Room: the compiler: 1.1.1'
Copy the code

For those of you who have read the previous article, you can put it directly in config. Gradle for unified management.

 dependVersion = [
 room_version       : '1.1.1'
 ]
      roomLib = [room_runtime: "android.arch.persistence.room:runtime:$dependVersion.room_version",
               room_rxjave2: "android.arch.persistence.room:rxjava2:$dependVersion.room_version"

    ]
    room = [ room: "android.arch.persistence.room:compiler:$dependVersion.room_version"]
    ]
    
     roomDeps = [roomLib.values()]
     roomDep = [room.values()]
 
Copy the code

Refer to it in the project

    implementation project.ext.roomDeps
    kapt project.ext.roomDep
Copy the code

Convenient for unified management. At this point, we can design a new structure as follows:

According to the structure drawing:

  1. View: the Activity/fragments
  2. ViewModel: Use RxJava to process data
  3. Local Data:Room
  4. Remote Data:Retrofit

The use of the Room

1. Create an Entity
Entity Indicates several commonly used attributes of an Entity
  1. Primary Key Each entity must define at least one field as the Primary key. Even if there is only one field, you must annotate it with @primarykey. If you want Room to set an autoGenerate ID for an entity, you can set @primaryKey’s autoGenerate property. If your entity has a combined primary key, you can use the primaryKeys property of the @Entity annotation.

2. TableName Room uses the class name as the tableName of the database by default. If you want to use a different name, use the tableName property of the @Entity annotation.

3.ColumnInfo Room Sets the field name as the column name of the database table by default. If you want column to have a different name, add the @columninfo attribute to field.

To make your queries more efficient, you may want to create indexes for specific fields. To index an Entity, add indices property in the @Entity annotation to list the fields that you want to place in the index or composite index. Sometimes, a field or several fields must be unique. You can achieve this by setting the @index annotation’s unique attribute to true.

Sometimes you might want to think of an entity or POJOs as a whole, even if the object contains several fields. In this case, you can use the @embedded annotation to indicate that you want to decompose an object into subfields of a table. You can then query these embedded fields just like any other individual fields.

Go back to our project and create our Entity:

package yang.cehome.com.mvvmdemo.model.local.dao import android.arch.persistence.room.Entity import Android. Arch. Persistence. The room. The PrimaryKey / * * * @ author yangzc * @ data 2018/11/7 10:23 * @ desc create Post Entity * * / @ the Entity  data class PostEntity( val message: String, @PrimaryKey val nu: String, val ischeck: String, val condition: String, val com: String, val status: String, val state: String )Copy the code
2. Create a Dao

Equivalent to the API in Retrofit.

The Dao is responsible for the method of manipulating the database, which means that some of our actions to manipulate the database are done here. The difference is that we don’t need all of these to define queries with annotations in Dao classes.

package yang.cehome.com.mvvmdemo.model.local.dao

import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy
import android.arch.persistence.room.Query
import io.reactivex.Single

/**
 * @author yangzc
 *	@data 2018/11/5 17:40
 *	@desc PostDao
 *
 */
@Dao
interface PostDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insetAll(postinfo: List<PostEntity>)


    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun inserttWeather(postinfo: PostEntity)

    @Query("SELECT * FROM postentity")
    fun getWeathInfo(): Single<PostEntity>

}
Copy the code
3. Create a database

Equivalent to creating a RetrofitClient object.

We need to create an AppDatabase class that contains all the entities and the DAO that operates on them. This class needs to inherit from the abstract classes of RoomDatabase

package yang.cehome.com.mvvmdemo.model.local import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context import yang.cehome.com.mvvmdemo.model.local.dao.PostDao import yang.cehome.com.mvvmdemo.model.local.dao.PostEntity /** * @author Yangzc * @data 2018/11/5 18:21 * @desc Contains all entities and DAO * */ @database (entities =) that operate on them arrayOf(PostEntity::class), version = 1) abstract class AppDatabase :RoomDatabase() { abstract fun WeatherDao(): PostDao 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()
    }
}

Copy the code

Ok The Room integration is complete

The project address

Github.com/yang0range/…