Home > Back-end >  Why my kotlin suspend function don't throw error? And continue to nextline?
Why my kotlin suspend function don't throw error? And continue to nextline?

Time:02-08

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()
 }

CodePudding user response:

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
    }
}
  •  Tags:  
  • Related