Execute AsyncTask like jquery’s $.ajax in Kotlin on Android

Last time I showed how to execute an AsyncTask in Jquery style. Now I will show how to do it in Kotlin.

Kotlin has much better support for functional programming, functions/lambdas are first class member of the language. A parameter of a method can be just typed function rather than having to be interface. So I don’t have to create interface for Func<T> and Action<T>.

This is how MyAsyncTask<T> looks like in Kotlin, note the type of task and completionHandler are ()->T or (T)->Unit?.

class MyAsyncTask<T>(private val task: () -> T) : AsyncTask<Void, Void, T>() {

  private var completionHandler: ((T) -> Unit)? = null

  private var errorHandler: ((Exception) -> Unit)? = null

  private var exception: Exception? = null

  fun setCompletionHandler(action: (T) -> Unit) {

      this.completionHandler = action


  fun setErrorHandler(action: (Exception) -> Unit) {

      this.errorHandler = action


  override fun doInBackground(vararg voids: Void): T? {

      try {

          return task.invoke()

      } catch (ex: Exception) {

          exception = ex


      return null


  override fun onPostExecute(result: T) {

      if (exception != null && errorHandler != null) {


      } else if (completionHandler != null) {





And here is Async<T>:

class Async<T> private constructor() {

  private var task: MyAsyncTask<T>? = null

  fun whenComplete(action: (T) -> Unit): Async<T> {


      return this


  fun onError(action: (Exception) -> Unit): Async<T> {


      return this


  fun execute() {

      try {


      } catch (ex: Exception) {




  companion object {

      fun <T> run(task: () -> T): Async<T> {

          val runner = Async<T>()

          runner.task = MyAsyncTask(task)

          return runner




Here is an example of how it is used.

override fun onCreate(savedInstanceState: Bundle?) {



  Async.run {

      val api = MyAPI()

      api.signInUser("user_name", "password")

  }.whenComplete {


  }.onError {




Print | posted on Friday, March 3, 2017 10:16 AM


# re: Execute AsyncTask like jquery’s $.ajax in Kotlin on Android

Left by Rajat at 6/13/2017 10:41 PM
Gravatar MyAPI() is undefined.
how to solve it.

# re: Execute AsyncTask like jquery’s $.ajax in Kotlin on Android

Left by Sawan Kumar at 6/15/2017 7:35 PM
Gravatar Kotlin 1.1.2 version out with 15 new features
Kotlin 1.1.2 version launched with some new features and resolves some bugs. I decided to research the upcoming changes released in past four EAP milestones and go through those that might impact Android Development.

Your comment:


Copyright © Changhong Fu

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski