0

I'm about to refactor my app to use a ViewModel. This is the database:

@Database(entities = [TimeStamp::class], version = 1, exportSchema = false)
abstract class RoomDB : RoomDatabase() {
    abstract fun timeStampDao(): TimeStampDao

    companion object {
        @Volatile
        private lateinit var db: RoomDB

        fun getInstance(context: Context): RoomDB {
            synchronized(this) {
                if (!::db.isInitialized) {
                    db = Room.databaseBuilder(context, RoomDB::class.java, "db").build()
                }
                return db
            }
        }
    }
}

And this is my ViewModel:

class MainViewModel : ViewModel() {

    val timeStamps: MutableLiveData<List<TimeStamp>> by lazy {
        MutableLiveData<List<TimeStamp>>().also {
            viewModelScope.launch {
                val timeStamps = RoomDB.getInstance(_NO_CONTEXT_).timeStampDao().getAll()
            }
        }
    }
}

Unfortunately, I don't have the context available in the ViewModel. Several answers to this question say that I should not try access the context in a ViewModel.

Do I need to refactor my RoomDB as well? Is there a generally accepted pattern how to do this?

user1785730
  • 3,150
  • 4
  • 27
  • 50
  • Like the top answer on the linked question says, you can use AndroidViewModel and get the context from its `application` property. By the way, your `getInstance` function could be improved (performance-wise) by making it double-checked and using nullability. – Tenfour04 May 23 '22 at 23:57
  • What do you by "making it double-checked"? – user1785730 May 27 '22 at 20:00
  • Change the `db` property to nullable instead of lateinit. Return `db ?: synchronized(this) {` and then do another null check inside the synchronization block in place of the `isInitialized` check. This means once the object is instantiated all future accesses of the object never have to acquire a synchronization lock again, which is better for performance. You can look up double-checked locked Java singletons for an explanation. – Tenfour04 May 27 '22 at 20:11

0 Answers0