Search code examples
androidandroid-architecture-componentsandroid-workmanager

Asynchronous Worker in Android WorkManager


Google recently announced new WorkManager architecture component. It makes it easy to schedule synchronous work by implementing doWork() in Worker class, but what if I want to do some asynchronous work in the background? For example, I want to make a network service call using Retrofit. I know I can make a synchronous network request, but it would block the thread and just feels wrong. Is there any solution for this or it is just not supported at the moment?


Solution

  • Per WorkManager docs:

    By default, WorkManager runs its operations on a background thread. If you are already running on a background thread and have need for synchronous (blocking) calls to WorkManager, use synchronous() to access such methods.

    Therefore, if you don't use synchronous(), you can safely perform sync network calls from doWork(). This is also a better approach from design perspective because callbacks are messy.

    That said, if you really want to fire async jobs from doWork(), you'll need to pause the execution thread and resume it upon async job completion using wait/notify mechanism (or some other thread management mechanism e.g. Semaphore). Not something I would recommend in most cases.

    As a side note, WorkManager is in very early alpha.