Skip to content

Instantly share code, notes, and snippets.

@IMoHaMeDHaMdYI
Last active March 16, 2019 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IMoHaMeDHaMdYI/255d21b5cf500fb7d5a84099a8885fad to your computer and use it in GitHub Desktop.
Save IMoHaMeDHaMdYI/255d21b5cf500fb7d5a84099a8885fad to your computer and use it in GitHub Desktop.
// Those are two tasks.
// TASK 1
open class SingletonHolder<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@Volatile
private var instance: T? = null
fun getInstance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
// Used Like This
@Database(entities = [User::class, Product::class], version = 1, exportSchema = false)
abstract class ECommerceDatabase : RoomDatabase()
{
companion object : SingletonHolder<ECommerceDatabase, Context>({
Room.databaseBuilder(
it.applicationContext,
ECommerceDatabase::class.java,
"ecommerce"
).build()
})
}
// -----------------
// second task
// Using higher order function find the solution :
// Describe what this function is doing
fun <T> Activity.startActivityFinishThis(target: Class<T>) {
val intent = Intent(this, target)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
// I want to add some custom behaviour on the intent in each activity I use this in.
startActivity(intent)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment