- Component package:
app.common.data.source.database.room
- DI integration:
app.di.platform.configureKoin
The integration includes the following components:
- AppDatabase: A pre-configured Room database designed to register all entities and DAO objects.
- AppRoomSource: Serves as a holder of the AppDatabase instance and acts as a service locator for all DAO objects.
- User and UserDao: An example entity and its associated DAO object. These classes serve as templates that can be used to create your own entities and DAOs.
The official guide for defining entities can be found here: https://developer.android.com/training/data-storage/room/defining-data
Imagine you need to add a new entity called Address. Here are the steps to follow.
You can use the User
class in app.common.data.source.database.room.entity
as a template.
@Entity(tableName = "address")
data class Address(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
@ColumnInfo(name = "country")
var country: String? = null,
@ColumnInfo(name = "city")
var city: String? = null,
@ColumnInfo(name = "street")
var street: String? = null,
)
You can use the UserDao
interface in app.common.data.source.database.room.dao
as a template.
@Dao
interface AddressDao {
@Insert
fun create(vararg addresses: Address)
@Update
fun update(vararg addresses: Address)
@Delete
fun delete(vararg addresses: Address)
@Query("SELECT * FROM address WHERE id = :id LIMIT 1")
fun get(id: Long): Address?
@Query("SELECT * FROM address")
fun getAll(): List<Address>
@Query("SELECT * FROM address")
fun getAllAsFlow(): Flow<Address>
}
@Database(
entities = [
Address::class
],
version = 1
)
abstract class AppDatabase : RoomDatabase() {
abstract fun getAddressDao(): AddressDao
}
class AppRoomSource(
private val databaseName: String = "db"
) {
...
val addressDao by lazy { db.getAddressDao() }
...
}
In this example, we will directly use AppRoomSource
from the ViewModel
to access AddressDao
. However, it is recommended to create a separate Repository
layer and call all data sources from there.
class AddressViewModel(
private val roomSource: AppRoomSource
) : BaseViewModel() {
val addresses = mutableStateOf(emptyList<Address>())
override fun doBind() = async("Get all addresses") {
val addressDao = roomSource.addressDao
addressDao.getAllAsFlow().collectLatest(addresses::value::set)
}
fun onCreate(address: Address) = async("onCreate", appState) {
val addressDao = roomSource.addressDao
addressDao.create(address)
}
fun onDelete(address: Address) = async("onRemove", appState) {
val addressDao = roomSource.addressDao
addressDao.delete(address)
}
}