Issue
This is my code in my viewModel which calls the function.
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!!)
)
}
}
I want to catch the error but it wont go to catch.
This is the suspend function
suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) =
withContext(ioDispatcher) {
applicationScope.launch{Body}.join()
}
Solution
It is because of this line:
applicationScope.launch {
Body
}
You are launching a new coroutine in a different coroutine scope. sendMessageWithMediaAudio
returns before the Body
completes. If you want to wait until sendMessageWithMediaAudio
completes (which probably is what you want looking at the call to .join()
), don't use applicationScope
, just launch the new coroutine in the scope provided by withContext
.
Also, launching a new coroutine and immediately waiting for it to complete (.join()
) isn't of any use. You can simply put the Body
directly inside withContext
.
suspend fun sendMessageWithMediaAudio(message: Message, uri: Uri, duration: Long) {
withContext(ioDispatcher) {
Body
}
}
Answered By - Arpit Shukla
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.