Skip to content

Instantly share code, notes, and snippets.

@adriantache
Created October 20, 2018 10:23
Show Gist options
  • Save adriantache/45e3540f47dcf9ac784cd2294661ac4f to your computer and use it in GitHub Desktop.
Save adriantache/45e3540f47dcf9ac784cd2294661ac4f to your computer and use it in GitHub Desktop.
//build an immediate OneTimeWorkRequest to fetch events from remote
OneTimeWorkRequest getEventJson = new OneTimeWorkRequest
.Builder(UpdateEventsWorker.class)
.setInputData(remoteUrl)
.addTag(EVENTS_JSON_WORK_TAG)
.build();
//we get a ListenableFuture<Void> from enqueue() which we can use below
//using beginUniqueWork to prevent re-enqueuing the same task while it is already running
ListenableFuture<Void> listenableFuture = WorkManager.getInstance().beginUniqueWork(EVENTS_JSON_WORK_TAG,
ExistingWorkPolicy.KEEP, getEventJson).enqueue();
//trigger additional tasks once the work is completed by calling addListener()
// and giving it a Runnable and an executor; I'm also running the code on the UI
// thread since it also impacts views etc. otherwise runOnUiThread is not needed
listenableFuture.addListener(() ->
runOnUiThread(MainActivity.this::onWorkCompleted), new CurrentThreadExecutor());
//[...]
//this is the code for the Executor I'm using due to import conflicts with Guava
//for a light load we could use a MoreExecutors.directExecutor()
class CurrentThreadExecutor implements Executor {
public void execute(@NonNull Runnable r) {
r.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment