Now I'm gradually mastering Android and I can not solve such a problem. I have such an ugly class that connects to the database, its instance is created in the repository and through the public field st: Statement I execute various requests, they are also similar through Thread and already in the ViewModel their results are assigned to LiveData.
class PostgreDatabase{
lateinit var st: Statement
var status = false
private lateinit var connection: Connection
init {
val user = "***"
val password = "***"
val url = "***"
val thread = Thread(Runnable {
kotlin.run {
try {
connection = DriverManager.getConnection(url, user, password)
st = connection.createStatement()
status = true
Log.d("SQL", "Connected: $status")
} catch (e: Exception) {
status = false
Log.d("SQL", e.message.toString())
e.printStackTrace()
}
}
})
thread.start()
try {
thread.join()
} catch (e: Exception) {
Log.d("SQL", e.toString())
}
}
}
I would like to do it all through coroutines, but it doesn't work for me. It turns out that the variables in the coroutine are not assigned values and, for example, after initializing this class, the connection remains empty, although in the log it seems to be successfully connected. As I understand it, the main thread somehow does not wait for the execution of the coroutine and therefore the values are not assigned.
How could this be implemented? Or maybe everything is completely bad and a completely different logic of work is needed for coroutines? Then I would like to ask for advice where to dig. Everything I find about coroutines seems to be not about breaking my head already.