best way for running code in async with kotlin

git :

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...
Clay07g :

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, then 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19991&siteId=1