0

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.

Z3RG
  • 1
  • 1
  • 1
    As it seems like you are connecting off the Android device to a Postgres DB, see: [JDBC vs Web Service for Android](https://stackoverflow.com/q/15853367/295004) – Morrison Chang Apr 02 '22 at 00:26
  • can you share the code you wrote that uses the coroutines? – Stachu Apr 02 '22 at 07:29
  • The main thread can't/shouldn't wait for anything, because that means the application freezes. This thread has to run all the time. To wait for something, you need to use callbacks or futures (threads) or suspend functions or flows (coroutines). Anyway, do you have to use JDBC specifically? There are DB tools that fit coroutines much better. See R2DBC or some DB framework designed specifically for coroutines. – broot Apr 02 '22 at 07:51

0 Answers0