Home > database >  Kotlin new Thread is still running on main thread
Kotlin new Thread is still running on main thread

Time:05-04

I am trying to make network calls on a background thread, so I am creating a thread like this:

private val networkThread = Thread("NetworkThread")

init {
    networkThread.start()
}

However when I try running something on the thread like this:

    networkThread.run {
        try {
            socket = Socket(ip, port)
        } catch (e: java.lang.Exception) {
            Log.e(TAG, "Network Error $e")
        }
    }

I get the following error: Network Error android.os.NetworkOnMainThreadException

Why is this still running on the MainThread? If I create the thread by using a runnable as the param it works, but I am just curious why doing it this way is still counting as the MainThread

CodePudding user response:

private val networkThread = Thread("NetworkThread") creates a thread which does nothing as you haven't override its run method.

networkThread.run {
        ....
}

run method you are using on networkThread is not the run() method of the Thread class but is the scope function of Kotlin which gives the context object as the receiver and returns the lambda result, that is why you are getting Network Error android.os.NetworkOnMainThreadException

For a thread to execute something on the background thread, you've to override its run method or you can create a Runnable and use it to create thread object

val networkThread = object: Thread() {
        override fun run() {
            try {
                socket = Socket(ip, port)
            } catch (e: java.lang.Exception) {
                Log.e(TAG, "Network Error $e")
            }
        }
    }
    
networkThread.start()
  • Related