Jérôme Gully
12/28/2018, 11:18 AMINSTANCE var is assigned to a tempInstance to check if it is null ? and why in the synchronizrd block the INSTANCE is assigned to instance and the instance is returned instead of INSTANCE ? I missunderstood something i guess.Andreas Sinz
12/28/2018, 11:50 AMval tempInstance = INSTANCE
if(tempInstance != null)
return tempInstance //Kotlin automatically casts tempInstance to WordRoomDatabase, because its a val and cannot be changed
vs
if(INSTANCE != null)
return INSTANCE //INSTANCE is still a WordRoomDatabase?, because theoretically it could've been set to null between the null check and the returnAndreas Sinz
12/28/2018, 11:51 AMINSTANCE and instance is the same at the end of the synchronized-block, so it doesn't matter which one is returnedJérôme Gully
12/28/2018, 12:39 PMJérôme Gully
12/28/2018, 12:40 PMif (INSTANCE != null) {
return INSTANCE as AppDatabase
}Jérôme Gully
12/28/2018, 12:41 PMJérôme Gully
12/28/2018, 12:51 PMfun getDatabase(context: Context): AppDatabase {
return if (INSTANCE != null) {
INSTANCE as AppDatabase
} else {
synchronized(this) {
Room.inMemoryDatabaseBuilder(
context.applicationContext,
AppDatabase::class.java
).build()
}
}
}
for a more idiomatic and functional way, do you thinks I'm right with that ?Andreas Sinz
12/28/2018, 12:52 PMJérôme Gully
12/28/2018, 12:54 PMAndreas Sinz
12/28/2018, 12:56 PMINSTANCE is never assigned. you need something like INSTANCE = Room.inMemoryDatabaseBuilder(...)Jérôme Gully
12/28/2018, 12:56 PMAndreas Sinz
12/28/2018, 12:58 PMif, when more often as expressions rather than statementsJérôme Gully
12/28/2018, 1:00 PMAndreas Sinz
12/28/2018, 1:09 PMJérôme Gully
12/28/2018, 1:12 PMAndreas Sinz
12/28/2018, 1:19 PMgetDatabase() is not called from different threads, otherwise it can lead to hard to debug problemsAlowaniak
12/28/2018, 5:17 PM.also { INSTANCE = it} in your version @Jérôme GullyAlowaniak
12/28/2018, 5:18 PMAndreas Sinz
12/29/2018, 10:37 AMsynchronized()-block is actually useless, the whole body should be synchronized