“Colorful software or web code on a computer monitor” by Markus Spiske on Unsplash

Jr Android Devs: A Background Job Helper Class For You!

To enable Jr Android Developers forget about handling bg job once and for all

Mayank
अहमस्मि योधः ||
2 min readMar 10, 2018

--

Most of the times we need to execute things in the background in Android to avoid blocking the main thread (aka UI thread). This is necessary to avoid application not responding dialogs and to provide an awesome UX to the user at all times.

But, doing tasks in a background thread in Android is a pain in the ass. You simply cannot just plug and play anything. You have to be cautious of memory leaks. And if you think Async Tasks are the way to go, think again.

Presenting BgJobHelper Class!

This class makes use of reactive programming (RxAndroid and RxJava) internally to enable developers do background jobs like it’s a child’s play. Via this, developers don’t need to worry about anything at all. Everything is taken care of by default.

ONE TIME SETUP

1

Import RxAndroid/RxJava by copying this code in your app level build.grade file:

Find latest version code of RxAndroid here.
Find latest version code of RxJava here.

2

Copy this class BgJobHelper.java in your project:

USAGE

1

In the Activity where you want to execute a task in background thread, declare this instance variable:

2

In the same Activity, initialize the variable in onCreate() :

3

In the same Activity, override onDestroy() to this (basically copy this code):

4.1

Finally, to execute a job in background thread, simply use the below code snippet:

4.2

In case you want to just do something in background, without caring about UI before/ after the job, use this method:

Happy Coding In The Background :)

--

--