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

On Android, if you want to make an async call, AsyncTask is the way to go. Basically you will have to implement something like this:


private class LongOperation extends AsyncTask<String, Void, String> {

  @Override

  protected String doInBackground(String... params) {

      //execute a long running operation

  }

  @Override

  protected void onPostExecute(String result) {

      //back to UI thread, can update UI

  }

}


Then you can call new LongOperation().execute("");


I don’t like having to write so much boilerplate code to just invoke a method asynchronously and I hate those mystical type parameters with AsyncTask. I want something simple, something like jquery’s $.ajax. I want write async code like this:


Async.run(() -> {

  //execute a long running operation

})

.whenComplete(result -> {

  //back to UI thread, can update UI

})

.onError(ex -> {

  //handle error, on UI thread

})


Here is how I do it.

First I need to create 2 interfaces:

public interface Action<T> {

  void execute(T param);

}


public interface Func<T> {

  T execute() throws Exception;

}


Then I need a wrapper on AsyncTask:


public class MyAsyncTask<T> extends AsyncTask<Void, Void, T> {


  private Func<T> task;

  private Action<T> completionHandler;

  private Action<Exception> errorHandler;

  private Exception exception;


  public MyAsyncTask(Func<T> task) {

      this.task = task;

  }


  public void setCompletionHandler(Action<T> action) {

      this.completionHandler = action;

  }


  public void setErrorHandler(Action<Exception> action) {

      this.errorHandler = action;

  }


  @Override

  protected T doInBackground(Void... voids) {

      try {

          return task.execute();

      } catch (Exception ex) {

          exception = ex;

      }

      return null;

  }


  @Override

  protected void onPostExecute(T result) {

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

          errorHandler.execute(exception);

      } else if (completionHandler != null) {

          completionHandler.execute(result);

      }

  }

}


Last, I need a small class to enable the fluent interface:


public class Async<T> {


  private  MyAsyncTask<T> task;


  private Async() {

  }


  public static <T> Async<T> run(Func<T> task) {

      Async<T> runner = new Async<T>();

      runner.task = new MyAsyncTask<T>(task);

      return runner;

  }


  public Async<T> whenComplete(Action<T> action) {

      task.setCompletionHandler(action);

      return this;

  }


  public Async<T> onError(Action<Exception> action) {

      task.setErrorHandler(action);

      return this;

  }


  public void execute() {

      try {

          task.execute();

      } catch (Exception ex) {

          ex.printStackTrace();

      }

  }

}



That is all I need!

Here is an example usage of it:


private void loadUser() {

  final Dialog progress = showProgressDialog();


  Async.run(new Func<UserInfo>() {

      @Override

      public UserInfo execute() {

          APIServer api = new APIServer()

          return api.loadUser();

      }

      })

      .whenComplete(new Action<UserInfo>() {

          @Override

          public void execute(UserInfo user) {

              progress.dismiss();

              //update user UI

              }

          }

      })

      .onError(new Action<Exception>() {

          @Override

          public void execute(Exception ex) {

              progress.dismiss();

              showAlertDialog(ex.getMessage());

          }

      })

      .execute();

}


Even simpler with lambda expression in Java 8!!!


In Java 8, an interface with single abstract method is a functional interface. A lambda expression with same signature (parameters and return type) as the interface method can be cast to the interface type automatically. As both Func and Action have only one method, they are functional interfaces. So we a method require a Func or Action as a parameter, we can pass in a lambda expression. If you want to know more about functional interface, this article is good to read.

So using lambda expression, we can make async call like this:


private void loadUser() {

  final Dialog progress = showProgressDialog();


  Async.run(() -> {

          APIServer api = new APIServer()

          return api.loadUser();

      })

      .whenComplete((user) -> {

          progress.dismiss();

          //update user UI

      })

      .onError((ex) -> {

progress.dismiss();

showAlertDialog(ex.getMessage());

      })

      .execute();

}


Print | posted on Wednesday, March 1, 2017 10:06 PM

Feedback

# Bayrak

Left by Elka Bayrak at 3/1/2017 10:37 PM
Gravatar thanks for sharing www.elkatabela.com

# Suberb Explanation

Left by Jack at 5/18/2017 2:35 AM
Gravatar Thanks for sharing a code which can be very useful if you are a android developer. Will to learn Dot Training and Certification visit JanBask Training for more details.

# Solitaire free online game

Left by solitaire at 5/30/2017 12:09 AM
Gravatar I was really happy to get the solitaire game and have the real online playground to play solitaire and enjoy the game free solitaire and have the great ideas to have the free game online solitaire from the website.

# Solitaire free online game

Left by solitaire at 5/30/2017 12:11 AM
Gravatar To play free solitaire free games that is from the website http://solitairetimes.com and have lots of free cards to play solitaire.

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

Left by solitaire at 5/30/2017 12:13 AM
Gravatar Thanks for the post solitaire

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

Left by bittu sa du at 6/28/2017 5:23 PM

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

Left by cdsf at 6/28/2017 5:25 PM

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

Left by sonia at 6/30/2017 8:28 PM
Gravatar I really like your post and I appreciate your hard work to write this post. escorts in Jaipur

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

Left by chelsieanayas at 7/20/2017 7:39 PM
Gravatar Just a smile and the rain is gone Can hardly believe it, yeah. There's an angel standing next to me. Reaching for my heart Just a smile and there's no way back .Can hardly believe it, yeah But there's an angel calling me. Reaching for my heart I know that I'll be okay now. This time, it's real I lay my love on you It's all I wanna do Every time I breathe I feel brand new You open up my heart Show me all your love and walk right through As I lay my love on you.
dumb ways to die
fireboy and watergirl 4

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

Left by Jenny at 7/30/2017 6:29 PM
Gravatar Great to see that someone still understand how to create an awesome blog. The blog is genuinely impressive in all aspects.

Your comment:





 

Copyright © Changhong Fu

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski