android - 条件失败时无法停止 CoroutineWorker

标签 android kotlin kotlin-coroutines android-workmanager

我正在使用 CoroutineWorker 来执行后台任务。这是代码 fragment

class SimpleWorker(context: Context) : CoroutineWorker(context, workerParams) {
     override suspend fun doWork(): Result = coroutineScope{
         //obtain settings info saved as local file
         val settingsInfo = obtainSettings(context) 

         if(null == settingsInfo) {
            Result.failure()
         }

         Log.i(TAG, "Valid settings found, proceed")
         val isUploadEnabled = settingsInfo.isUploadEnabled //error when settingInfo is null
      }
}

如果设置为空,我希望工作人员发送失败信号并停止运行其余代码。相反,它会继续前进并进一步分解。 Result.failure() 是否没有做它应该做的事情或者我错过了什么?

最佳答案

您必须使用 Result.failure() 对象实际调用 return:

if(null == settingsInfo) {
    return@coroutineScope Result.failure()
}

否则,您只是创建一个 Result.failure() 对象,而不用它做任何事情。

关于android - 条件失败时无法停止 CoroutineWorker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64472566/

相关文章:

android - SIP 如何在蜂窝网络上工作?

generics - 如何在伴随对象中使用泛型

kotlin - 如何从另一个类(在 Kotlin 中)退出 runBlocking 协程?

android - 如何在主线程上使用协程 GlobalScope?

Android 模拟器从其他主机访问 redir 端口

android - 在 kitkat android 中运行同一应用程序的多个实例

android - Firebase 在尝试启动 robotest 时显示 "You do not have permission to create a test matrix with Test Lab."

android - 错误 : Unresolved reference: DaggerAppComponent

android - ApolloGraphql 文件未找到异常 : source/apollo/generatedIR/debug/src (Is a directory)

android - 不适当的阻塞方法调用,但暂停函数 'withContext' 只能从协程或另一个暂停函数中调用