Search code examples
androidkotlinandroid-asynctask

Optimal solution for utilizing the same AsyncTask repeatedly?


I know that an AsyncTask can be run only once. I know a way around that, but I need a variable from the AsyncTask that uses complicated(?) processes. This is my code for calling the AsyncTask

val thr=NewTask()
    thr.delegate = this
    button.setOnClickListener {
        thr.execute()
    }

NewTask.doOnBackground() is just a normal method sending the request to the URL. onPostExecute() is a bit different:

public override fun onPostExecute(result: String?) {
    //super.onPostExecute(result)
    delegate!!.processFinish(result!!)
}

with delegate being a variable of AsyncResponse? which is an interface containing processFinish abstract method taking a string and returning nothing.

My question is, how can I run the AsyncTask repeatedly while still getting the response? Thanks in advance.


Solution

  • Finally, I settled on using coroutines with this. Coroutines are easy to use, much easier than AsyncTask. I don't know why I was scared of them. Here is the code I used:

    class CoRoutine{
    suspend fun httpGet(url: String = "https://boogle.org"): String {
        val arr = ArrayList<String>()
        withContext(Dispatchers.IO) {
            val url = URL(url)
    
            with(url.openConnection() as HttpURLConnection) {
                requestMethod = "GET"  // optional default is GET
    
                //arr.add(responseCode)
    
                inputStream.bufferedReader().use {
                    it.lines().forEach { line ->
                        //println(line)
                        arr.add(line as String)
                    }
                }
            }
        }
        return arr.get(0)
    }
    }