SugarTask: An Elegant Alternative to AsyncTask

Hey guys, today I’m going to show you an elegant, lifecycle-safe alternative to AsyncTask. It’s a library called “SugarTask”. You can find its GitHub page right here: https://github.com/mthli/SugarTask

So, let me quickly show you how to use it in your project. First, you need to add the following to your project-level “build.gradle” file:

Then, you need to add the following dependency to your module-level “build.gradle” file:

Now, we’re ready to go. Let me provide an example code snippet where I use SugarTask first, then I will talk about it thoroughly:

As you can see, I chained some method calls here:  with(), assign(), and execute() are the required ones, whereas the others are optional. I will go through each of them one by one:

  • with(): SugarTask hooks itself to the given Activity/Fragment through this method. It helps SugarTask cancel all callbacks when  onStop() is called for Activity/Fragment.
  • assign(): Takes a TaskDescription instance with an overridden onBackground() method where we code our background job. If we need to notify UI thread during background job process, we simply call SugarTask.post(message) to send stuff to UI thread.
  • handle(): Takes a MessageListener instance with an overridden handleMessage() method where we code what we do when a notification message is received during background job process. This message can contain any process-related object you may need on UI thread.
  • finish(): Takes a FinishListener instance with an overridden onFinish() method where we code what we do when background job is completed successfully. If onBackground() method returns a resulting object, we can handle that here as well.
  • broken(): Takes a BrokenListener instance with an overridden onBroken() method where we code what we do with the exception if something unexpected happens during background job process.
  • execute(): Starts execution of task.

That’s all for today. If you have any question regarding this post, leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *