Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet111/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   107   108   109   110   111   112   113   114   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

126
CHAPTER 8: APIs
The builder allows for certain configuration activities in a fluent builder style. Interesting 
configuration options are shown in Table 
8-1
. You just chain them before the final .build() 
call. One option you might use often during early development phases is relaxing the 
foreground operation restriction by using this:
fun fetchDb() =
Room.databaseBuilder(
this, MyDatabase::class.java,
"MyDatabase.db")
.allowMainThreadQueries()
.build()
val db = fetchDb()
Table 8-1. Room Builder Options
Option
Description
addCallback(RoomDatabase.Callback)
Use this to add a RoomDatabase.Callback to this database. 
You can use it, for example, to have some code 
executed when the database gets created or opened.
allowMainThreadQueries()
Use this to disable the no main thread restriction in Room. 
If you don’t use this and try to perform database operations 
in the main thread, Room will throw an exception. There 
is a good reason for Room to work this way. GUI-related 
threads should not be blocked because of lengthy 
database operations. So, for your code you should not call 
this method; it makes sense only for experiments to avoid 
dealing with asynchronicity.
addMigrations(vararg Migration)
Use this to add migration plans. Migration is covered in 
more detail later in the chapter.
fallbackToDestructiveMigration()
If a matching migration plan is missing (for example, 
for a necessary upgrade from the data version inside 
the database to the version specified in the @Database 
annotation, no registered migration plan can be found), 
Room normally throws an exception. If you instead want 
the current database to be purged and then the database 
be built up from scratch for the new version, use this 
method.
fallbackToDestructive 
Migration(vararg Int)
This is the same as fallbackToDestructiveMigration() but 
restricted to certain starting versions. For all other versions
an exception will be thrown if the migration plan is missing.
Then, once you have a database object, just call any of the DAO factory methods we 
defined inside the database class in an abstract manner, and Room automatically provides 
implementations. So, for example, write the following:
val db = ...
val employeeDao = db.employeeDao()
// use the DAO...



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   107   108   109   110   111   112   113   114   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling