Skip to content

Instantly share code, notes, and snippets.

@damiancastelao
Last active December 2, 2022 11:24
Show Gist options
  • Save damiancastelao/1717a68fa7d4ccc0e1e63ca7450e32f8 to your computer and use it in GitHub Desktop.
Save damiancastelao/1717a68fa7d4ccc0e1e63ca7450e32f8 to your computer and use it in GitHub Desktop.
/**
* Clase para acceder a la base de datos y al DAO
**/
class MyViewModel(application: Application) : AndroidViewModel(application) {
// definimos el context para crear el room
private val context = getApplication<Application>().applicationContext
// Objeto para el acceso a la BD utilizando Room
roomMiDB = Room
.databaseBuilder(context,
RecordDB::class.java, "records")
.build()
// Corrutina para utilizar el DAO
val roomCorrutine = GlobalScope.launch(Dispatchers.Main) {
try {
// actualizamos el valor de record
record.value = roomMiDB!!.recordDao().getPuntuacion()
} catch(ex : NullPointerException) {
// insertamos si no hay puntuacion guardada
roomMiDB!!.recordDao().crearPuntuacion()
// actualizamos el valor de record
record.value = roomMiDB!!.recordDao().getPuntuacion()
}
}
// inicializamos la corrutina
roomCorrutine.start()
(...)
} // fin de la clase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment