onPostExecute in anko doAsync

6.2k views Asked by At

I know there are two methods available to do AsyncTask in Anko library.

  1. doAsync()

  2. doAsyncResult()

My question is both the above methods have onComplete() method. In both method's onComplete() there is no trace of result like AsyncTask.onPostExecute().

Example:

        doAsync {
            sdkServiceFactory.initSDKService()
            onComplete { Log.d("Controller", "Sdk Connected") }
        }

   val result = doAsyncResult {
                  onComplete { Log.d("Controller", "Sdk Connected") }
                  sdkServiceFactory.initSDKService()
                }.get()

In either method, I can get only the completed callback not the result. What are the similar methods available in Anko library for AsyncTask.onPreExecute() and AsyncTask.onPostExecute().

1

There are 1 answers

0
Brian On BEST ANSWER

doAsync is used to execute code on a different thread, but does not return anything to the main thread when finished.

doAsyncResult is used to perform an activity on a separate thread, and the execute an operation on the main thread after completing execution on the separate thread.

To push anything to the main thread, add a new block with

uiThread {
        //write you code here
    }

in it.

Or better yet, create the method that you want to run asynchronously as a function with a return value. Then pass the method in to the doAsync call. To quote an example:

 val longRunningTask: (AnkoAsyncContext<ListView>.() -> ArrayList<String>) = {
                ::doAnIntensiveActivity.invoke()
            }
 val f : Future<ArrayList<String>> = doAsyncResult(null, longRunningTask)