0

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.

Timotej Leginus
  • 304
  • 3
  • 18
  • Since `AsyncTask` is likely to be deprecated in ~2 months, I recommend you migrate to something else (probably coroutines, since you are using Kotlin). – CommonsWare Jan 11 '20 at 20:04
  • Can you suggest some resources as to how to move to coroutines? – Timotej Leginus Jan 11 '20 at 20:05
  • I do not know of anything off the top of my head specifically for migrating from `AsyncTask` to coroutines, though I've just added that to my list of blog post topics to write about... :-) I cover coroutines in [this book](https://commonsware.com/Coroutines) and have several samples in [this book](https://commonsware.com/Jetpack) that use them. For example, [this sample app](https://gitlab.com/commonsguy/cw-jetpack-kotlin/tree/v0.6/DiceLight) and [this sample app](https://gitlab.com/commonsguy/cw-jetpack-kotlin/tree/v0.6/Diceware) each implement "diceware" apps using coroutines. – CommonsWare Jan 11 '20 at 20:21
  • 2
    Thank you CommonsWare for this! It was very easy to set up with Coroutines, I was scared of this at first, but now the code is 60 lines shorter. Thank you! – Timotej Leginus Jan 11 '20 at 20:29

1 Answers1

0

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)
}
}
Timotej Leginus
  • 304
  • 3
  • 18