我正在使用 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/