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.

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

Left by Kritika at 8/21/2017 10:41 PM
Gravatar I think you are totally right at this point - Jaipur call girls

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

Left by Ritu Rai at 8/22/2017 11:34 PM
Gravatar I am really very impressed to see this lovely event - Udaipur call girls

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

Left by Simran at 8/29/2017 6:24 PM
Gravatar I really like your post Jaipur Escort Service

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

Left by Alice at 9/9/2017 12:14 AM
Gravatar really? I like it nutella recall

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

Left by h isam at 9/13/2017 3:25 AM
Gravatar I really like this article, very help me in my work. thank you
by h isam

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

Left by Micel at 9/16/2017 4:17 PM
Gravatar I like the style of writing you, I wait for the next update.

viagra

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

Left by benchfolks at 9/19/2017 12:36 AM
Gravatar I don’t know anything about AJAX TRAINING. But interested in learning the code. Here you share some code in AJAX and HTTPS and it's very easy to understand. Please explain the code portion in detail.

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

Left by maodzedun at 9/21/2017 2:04 AM
Gravatar Thanks for this simple and elegant solution, I myself would not have thought of doing this food places near me

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

Left by Computer Geek at 10/2/2017 2:01 AM
Gravatar The best site. I want to share about our link back. Don't forget, we'll see the latest from you, thank you. 2018 ford mustang gt

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

Left by kavya at 10/4/2017 1:32 AM
Gravatar Thanks for sharing simple java script which can help us more. https://bangalorehotcallgirl.quora.com/Hire-VIP-Call-Girls-in-Bangalore-Escorts

# Russian Escorts in Delhi

Left by Sadiya Khan at 10/4/2017 6:31 PM
Gravatar Very helpful fot people and i am so happy for visit herre.
Russian Escorts in Delhi

# Sexy Jaipur Escorts Service

Left by Simran at 10/13/2017 6:12 PM
Gravatar This is the very very good post and really it is the very good post for all the people.
Sexy Jaipur Escorts Service

# Female Independent Escorts

Left by Nikita at 10/16/2017 11:11 PM
Gravatar
Nice! I want you to thank for your time of this wonderful read!!! Your blog posts are more interesting and informative. I very like and visit regularly.
Female Independent Escorts

Your comment:





 

Copyright © Changhong Fu

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski