android – best way for running code in async with kotlin-ThrowExceptions

Exception or error:

hi i want use jsoup to load a large table from html, what is the best way for doing this in async way?
AsyncTask? coroutines? doasync library? which one? i need show progressbar while fetching data so please tell me what is the best way?

UPDATE:
i want run this code in async

doc: Document = Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
// some code for parsing...
How to solve:

In Kotlin, the general approach is coroutines, but normal threading is also a completely fine option, depending on what you’re doing.

For example, if your operation is a thread-blocking operation, it actually can’t run safely in a coroutine unless it’s dispatched in a separate thread. For coroutines, you need to know the difference between suspending and blocking (huge difference).

So if reading the HTML table is a blocking operation, and you don’t need to integrate with other coroutines, than a normal thread works just fine. There are many Java examples that are transferable to Kotlin.

With coroutines, you can do something like:

suspend fun getDoc() = withContext(Dispatchers.IO) {
    Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
}

Then, in your main code:

fun main() = runBlocking {

    val deferredDoc = async { getDoc() }

    // Do whatever.... it's not being blocked...

    val doc = deferredDoc.await() // SUSPENDING CALL - but not blocking
}

Obviously, your program’s structure will look different than this example, because it depends entirely on what code you want to execute asynchronously with “getDoc()”.

For example, you can even have another coroutine that executes while “deferredDoc.await()” is suspending, without even creating another thread. That’s the benefit of coroutines.

In the structure above, we have 3 guaranteed threads:

  • Main thread, which is always blocked
  • Main Coroutine thread. This is what the coroutines generally run on. Kotlin coroutines will run your coroutines asynchronously inside this thread using suspension.
  • IO thread. This is what your blocking code will run on.

###

I’ll advice you try out Kotlin Coroutines. This would enable you dispatch expensive or long-running operations i.e. querying databases, making network requests/calls off to other threads thereby not blocking the Main Thread. Coroutines help you avoid the hassle of callbacks. Also, Google deprecated the AsyncTask API (in Android 11) and recommends using Java’s Concurrency framework or Kotlin Coroutines as the way to go for multi-threading purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *