Optimal solution for utilizing the same AsyncTask repeatedly?

自闭症网瘾萝莉.ら 提交于 2020-02-06 07:44:52

问题


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.


回答1:


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)
}
}


来源:https://stackoverflow.com/questions/59698190/optimal-solution-for-utilizing-the-same-asynctask-repeatedly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!