-
Notifications
You must be signed in to change notification settings - Fork 395
Canceling Jobs
It is a common requirement that sometimes you notice a Job will not be needed anymore, like when a user leaves an activity or a user cancel an operation.
To achieve this, you can use job tags to identify your Jobs and later reference them to cancel using JobManager#cancelJobs or JobManager#cancelJobsInBackground.
Note that if a job is already running when cancel request arrives, JobManager will wait until Job#onRun method finishes (so no thread interrupts to stop the job). If you have a long running onRun
method, you can check Job#isCancelled and if it returns true, just throw an exception to immediately stop the Job.
Here is an example on how you could cancel all jobs created for an Activity when it becomes invisible. This sample uses onStart
& onStop
tuple, but you could as well use onCreate
and onDestroy
.
public class BaseActivity extends Activity {
...
// a random string identifier that is generated when Activity becomes visible
private String sessionId;
// preferably injected
private JobManager jobManager;
public String getSessionId() {
return sessionId;
}
@Override
protected void onStart() {
super.onStart();
sessionId = UUID.randomUUID().toString();
}
@Override
protected void onStop() {
super.onStop();
jobManager.cancelJobsInBackground(null, TagConstraint.ANY, sessionId);
}
}
Now, in an activity that extends this BaseActivity
, you can create jobs that will automatically be cancelled when Activity goes to background as follows:
abstract class ActivityBoundJob extends Job {
public ActivityBoundJob(BaseActivity activity, Params params) {
super(params.addTags(activity.getSessionId()));
}
}