Room — ORM для SQLite базы данных. Преимущества:
Пример использования:
@Entity(tableName = "cinema")
data class CinemaScheme(
@PrimaryKey @ColumnInfo(name = "cinema_id") val id: Long,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "mail") val mail: String,
@ColumnInfo(name = "address") val address: String,
@ColumnInfo(name = "latitude") val latitude: Double,
@ColumnInfo(name = "longitude") val longitude: Double,
@ColumnInfo(name = "city_id") val cityId: Long,
@ColumnInfo(name = "is_favorite") val isFavorite: Boolean,
@ColumnInfo(name = "subway_stations") val stations: Array<DataSubwayStation>?) {
}
@Dao
interface CinemaDao {
@Query("SELECT * FROM cinema WHERE city_id = :cityId")
fun subscribeToAllByCity(cityId: Long): Flowable<List<CinemaScheme>>
@Query("SELECT * FROM cinema WHERE city_id = :cityId")
fun getAllByCity(cityId: Long): Single<List<CinemaScheme>>
@Query("SELECT * FROM cinema WHERE cinema_id = :cinemaId")
fun getCinema(cinemaId: Long): Single<CinemaScheme>
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveCinemas(items: List<CinemaScheme>)
}
@Module
class DataBaseModule {
@Provides
@ApplicationScope
fun provideProjectDataBase(application: Application): ProjectDataBase {
return Room.databaseBuilder(application, ProjectDataBase::class.java, "kinogolic-database").build()
}
@Provides
@ApplicationScope
fun provideCinemaDao(database: ProjectDataBase) = database.cinemaDao()
}
Настройка работы Room с базой данных в приложении осуществляется в DataBaseModule, который инклюдится в DataModule
@Database(entities = arrayOf(CityScheme::class, CinemaScheme::class), version = 2, exportSchema = false)
@TypeConverters(Converters::class)
abstract class ProjectDataBase : RoomDatabase() {
abstract fun cinemaDao(): CinemaDao
}
После объект интерфейса CinemaDao используется как поле в CinemaRepository.