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?