WorkManager:无需执行任何工作即可从startWork()正确退出 [英] WorkManager: exiting properly from startWork() without doing any work

查看:85
本文介绍了WorkManager:无需执行任何工作即可从startWork()正确退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我安排好的定期工作请求运行时,可能是我不想当时做任何工作,而只是等待定期系列中的下一个工作.

When my scheduled periodic work request runs, it may be the case that I don't want it to do any work at that time, and just wait for the next in the periodic series.

目前,我正在通过将 Completer 设置为成功状态并在触发异步工作资料之前返回来处理此问题,如下所示:

At present I'm handling this by setting the Completer to a success state and returning before firing the async work stuff, like so:

public ListenableFuture<Result> startWork() {
    return CallbackToFutureAdapter.getFuture(completer -> {
        if ( notThisTime() ) {
            completer.set(Result.success());
            return "nothing to do this time";
        }
        // the following will call completer.set(Result.success()) when it is finished...
        startSomeAsyncStuff(completer);
        return "started some async stuff";
    });
}

这应该怎么做?还是我应该运行 notThisTime()之前检查 getFuture()并返回设置为完成状态的 ListenableFuture 或类似的内容?

Is this how it should be done? Or should I be running the notThisTime() check before getFuture() and returning a ListenableFuture set to a completed stated, or something like that?

推荐答案

是的,这是正确的处理方式.

Yes, this is the correct way of doing things.

除非您全部拉入番石榴,否则创建 ListenableFuture 对象的唯一方法是通过 CallbackToFutureAdapter.getFuture ,因此,您必须始终调用它以获取访问权限到 completer 并调用 set(Result.success()).

Unless you pull in all of Guava, the only way to create a ListenableFuture object is via the CallbackToFutureAdapter.getFuture, therefore you have to call that anyways to gain access to the completer and to call set(Result.success()).

startWork() getFuture lambda都在主线程上运行,因此在该线程上阻塞工作同样不安全,因此应确保> notThisTime()可以安全地在任一位置的主线程上运行.

Both startWork() and the getFuture lambda run on the main thread, so it is equally not safe do blocking work there, so you should make sure your notThisTime() is safe to run on the main thread in either place.

这篇关于WorkManager:无需执行任何工作即可从startWork()正确退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆