问题描述
Google 最近发布了新的 WorkManager
架构组件.通过在 Worker
类中实现 doWork()
可以很容易地安排同步工作,但是如果我想要怎么办在后台做一些异步工作?例如,我想使用 Retrofit 进行网络服务调用.我知道我可以发出同步网络请求,但它会阻塞线程并且感觉不对.是否有任何解决方案或目前不支持?
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?
推荐答案
Per WorkManager文档:
默认情况下,WorkManager 在后台线程上运行其操作.如果您已经在后台线程上运行并且需要同步(阻塞)调用 WorkManager,请使用 synchronous() 来访问此类方法.
因此,如果您不使用synchronous()
,您可以安全地从doWork()
执行同步网络调用.从设计的角度来看,这也是一种更好的方法,因为回调很混乱.
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.
也就是说,如果您真的想从 doWork()
触发异步作业,您需要暂停执行线程并在异步作业完成后使用 wait/notify
机制(或其他一些线程管理机制,例如 Semaphore
).在大多数情况下,我不建议这样做.
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.
顺便提一下,WorkManager 还处于非常早期的 alpha 阶段.
As a side note, WorkManager is in very early alpha.
这篇关于Android WorkManager 中的异步工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!