Last active
March 14, 2025 02:53
-
-
Save tberghuis/f06cbfd1378eb2db84c394e37fcb8737 to your computer and use it in GitHub Desktop.
AppSingleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.myapplication | |
import android.app.Application | |
import android.content.Context | |
import androidx.room.Room | |
import androidx.room.RoomDatabase | |
private class AppSingleton private constructor(application: Application) { | |
val appDatabase by lazy { | |
Room.databaseBuilder( | |
application, | |
AppDatabase::class.java, | |
"room.db" | |
) | |
.build() | |
} | |
// ... more lazy properties | |
companion object { | |
@Volatile | |
private var instance: AppSingleton? = null | |
fun getInstance(context: Context): AppSingleton { | |
return instance ?: synchronized(this) { | |
instance ?: AppSingleton(context.applicationContext as Application) | |
} | |
} | |
} | |
} | |
val Context.appSingleton: AppSingleton | |
get() = AppSingleton.getInstance(this) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment