Triggering a method after WorkManager completion

A simpler guide to get you up to speed

Adrian Tache
Oct 20, 2018 · 2 min read

EDIT: As of Work 1.0.1 there is a much simpler way to do this, check out the bonus step of my newer article:

In spite of the official guide to WorkManager, we can no longer use observe() to trigger a method once work is complete starting with alpha-10.

As such, I’ve taken the time to research how we’re supposed to use the new way WorkManager functions. It has not been easy since documentation is pretty limited so far and my level of Java isn’t up to the standard that I fully understand the changes intuitively.

This is precisely how this change makes me feel. Source:

A major change in WorkManager alpha-10 is that WorkManager.enqueue() now returns a ListenableFuture<Void> which can be used to detect when the work is finished. ListenableFuture is an interface which extends Future and has only one method: void addListener(Runnable listener, Executor executor);

As such, the code from my previous post becomes:

The important part is that, as I mentioned above, we get a ListenableFuture from our WorkManager which triggers a runnable listener via an executor we designate when we call listenableFuture.addListener(). Technically, we can also use listenableFuture.get() to do this, but I haven’t yet figured out how.

Then, once the work is completed, the listener we’re designated is run. I’ve used a lambda in the code above, but if you’re not on Java 8 the code is basically just new Runnable() { @Override public void run() { this.onWorkCompleted }} which refers to a method called onWorkCompleted in the same class.

As mentioned above, the other argument we pass to addListener() is an executor, which for light workloads is simply MoreExecutors.directExecutor(), but in my case this created a weird conflict with the Guava import so I found a different solution.

That’s about as easy as it gets, hope it was clear and will help those who, like myself, have little experience and need to keep using WorkManager. Please let me know below in the comments if you have any questions or, more importantly, any suggestions or tips as to how to use or understand this better.

Finally, here’s an interesting video if you want to learn more about ListenableFuture:

Code Bites — Guava’s ListenableFuture

Thanks for reading this article. You can connect with me on LinkedIn.

If you liked this article, please hit the clap icon 👏 to show your support.

Adrian Tache

Written by

Mobile Developer 📱

Android Ideas

A collection of articles about Android Development

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade