为什么我的 kotlin 挂起函数不抛出错误?并继续下一行?



这是我的viewModel中调用函数的代码。

viewModelScope.launch {
resource.postValue(Resource.loading(true))
try {
localRepository.insertFile(fileEntity)
///This lines throw exeption
messageRepository.sendMessageWithMediaAudio(message, mediaUri,        duration)
///But still continue to this line and don't catch the error
resource.postValue(Resource.success(true))
} catch (exception: Exception) {
Timber.e(exception)
resource.postValue(
Resource.error(exception, exception.message!!)
)
}
}

我想抓住这个错误,但它抓不住。

这是暂停功能

suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) =
withContext(ioDispatcher) {
applicationScope.launch{Body}.join()
}

这是因为这行:

applicationScope.launch { 
Body 
}

您正在不同的协同程序范围中启动一个新的协同程序。CCD_ 1在CCD_ 2完成之前返回。如果您想等到sendMessageWithMediaAudio完成(这可能是您想要查看对.join()的调用(,请不要使用applicationScope,只需在withContext提供的范围内启动新的协同程序即可。

此外,启动一个新的协同程序并立即等待它完成(.join()(也没有任何用处。您可以简单地将Body直接放在withContext中。

suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) {
withContext(ioDispatcher) {
Body
}
}

最新更新