0

Recently I am trying to use androidx.work.* stuff to perform background tasks. It works fine with the MVVM pattern. However, I met several issues when using the Worker(via OneTimeWorkRequest.Builder) to replace the AsyncTask.

First, how to pass out generic object result back from the Worker? It seems only primitive types are supported. What if I want to decode the image file in the worker thread and pass the decoded drawable or bitmap back to the main thread observer? I have a workaround is to put the object in some global data store but it does not seem to be a good practice.

Another problem is that when I try to observe on the live data obtained via WorkManager.getWorkInfosByTagLiveData(TAG_NAME), it will also return the former en-queued worker info to me. So I have to call WorkManager.pruneWork() to avoid this issue. And this does not seem to be a good practice either.

Thanks for your advice.

Stanley Ko
  • 3,383
  • 3
  • 34
  • 60
Robin
  • 10,052
  • 6
  • 31
  • 52
  • Yes I have passed the Uri of the image and let the worker to decode it. The question is how to pass the decoded bitmap or drawable back gracefully? – Robin Mar 21 '19 at 03:19
  • I saw that codelab and learnt from it for the Worker stuff. And I don't like the way it passes the data - through a content provider, which is just way too heavy for a simple decode request. Maybe I am thinking to much, I should stick to use simple AsyncTask. – Robin Mar 21 '19 at 03:30
  • 2
    That's not really what WorkManager is meant for. Its meant for doing long term background type tasks. Like if you want to download dozens of stories from a newsfeed and write it to a local cache for later use. Its not meant for tasks that are meant to run immediately and update the UI. – Gabe Sechan Mar 21 '19 at 03:35
  • Rather than work manager, you could use Rxjava or Executors for immediate background tasks. Work manager is designed to do long term background tasks which can be delegated. – p.mathew13 Mar 21 '19 at 06:45

1 Answers1

0

Regarding returning the result: Simply put, the same way you do it with AsyncTask. You're not supposed to pass objects around in between task. Use a "callback" or interface like explained in this answer:

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

CaptainCrunch
  • 1,230
  • 14
  • 15