Исключение при использовании сопрограмм Kotlin для вызова APIAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Исключение при использовании сопрограмм Kotlin для вызова API

Сообщение Anonymous »

Я не очень хорошо владею английским, извините за возможные ошибки, это мой первый вопрос, у нас есть приложение, разработанное в Android Studio, которое выдает ошибку в библиотеке kotlinx.coroutines, ниже я привожу более подробную информацию:

Код: Выделить всё

FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.*.*.*, PID: 27311
kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for CancellableContinuation(DispatchedContinuation[Dispatchers.IO, Continuation at com.*.*.*.navs.main.MainViewModel$retrieveVisitsAvailable$1.invokeSuspend(MainViewModel.kt:187)@eaad1db]){Completed}@50e4478.  Please read KDoc to 'handleFatalException' method and report this incident to maintainers
at kotlinx.coroutines.DispatchedTask.handleFatalException$kotlinx_coroutines_core(DispatchedTask.kt:146)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:117)
at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:103)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
Suppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [StandaloneCoroutine{Completed}@5c37aea, Dispatchers.IO]
Caused by: java.lang.ClassCastException: kotlin.coroutines.jvm.internal.CompletedContinuation cannot be cast to kotlinx.coroutines.internal.DispatchedContinuation
at kotlinx.coroutines.CoroutineDispatcher.releaseInterceptedContinuation(CoroutineDispatcher.kt:166)
at kotlin.coroutines.jvm.internal.ContinuationImpl.releaseIntercepted(ContinuationImpl.kt:118)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:39)
Функция, которую помечает стек трассировки, следующая:

Код: Выделить всё

fun retrieveVisitsAvailable(currentLoc: Location) = viewModelScope.launch(Dispatchers.IO) {
if (connectivityManager.isNetworkAvailable()) {
try {
// The next function call is where the error is marked
VisitRepository.getVisitsAvailable(
_uiState.value.preferences!!.userId() !!
).collect {
result - >
when(result.status) {
HttpResult.Status.SUCCESS - > {
resetLoadingMessage()
if (result.data != null) {
setVisitsOverview(result.data.map {
it.copy(
distance =
if (it.lat != null && it.lng != null) {
SphericalUtil.computeDistanceBetween(
LatLng(currentLoc.latitude, currentLoc.longitude),
LatLng(it.lat.toDouble(), it.lng.toDouble())
).toFloat() / 1000
} else {
0 f
}
)

}.sortedBy {
it.distance
})
setHSButtonEnabled(true)
} else {
setErrorMessage(R.string.no_visits_available_lb)
//TODO: show message that no visits are available
// and block start and end day buttons
}
}

HttpResult.Status.ERROR - > {
resetLoadingMessage()
result.error ? .printStackTrace()
if (isNotConnectionError(result.error ? .javaClass ? .name)) {
setRemoteErrorMessage("Hay problemas en la conexión a internet, cargados los datos guardados.")
} else {
setRemoteErrorMessage(result.message!!)
}
setVisitsOverview(null);
//TODO: block start and end day buttons
}

HttpResult.Status.LOADING - >  {
setLoadingMessage(R.string.retrieving_visits_overview_lb)
}
}
}
} catch (e: Exception) {
e.printStackTrace();
}
} else {
setVisitsOverview(null);
}
}
По тому, что я отладил, функция выполняется корректно, если есть соединение, происходит вызов API и информация принимается корректно, она возвращается и завершается, но через некоторое время появляется исключение и приложение закрывается, попытка catch, похоже, не имеет никакого эффекта, и похоже, что функция больше не выполняется, эта функция выполняется в начале приложения, поскольку она загружает важную информацию для его работы - процесс, который работает корректно, но сбой происходит всегда, либо сразу, либо через несколько секунд или минут (максимум 2).
Это последующие вызовы:

Код: Выделить всё

class VisitRepository {
companion object {
suspend fun getVisitsAvailable(userId: Long): Flow  {
return flow {
emit(HttpResult.loading())
val result = VisitsDataSource.getVisitsAvailable(userId)
emit(result)
}.flowOn(Dispatchers.IO)
}
}
}

// VisitsDataSource
class VisitsDataSource {
companion object {
private val dataService = RESTClient.getService(Service::class.java)
suspend fun getVisitsAvailable(userId: Long): HttpResult =
RemoteDataSource.parseResponse {
dataService.getVisitsAvailable(userId)
}
}
}

// RemoteDataSource.parseResponse
interface RemoteDataSource {
companion object {
@JvmStatic
suspend fun  parseResponse(request: suspend() -> Response  ): HttpResult  {
var fallbackMessage = "Hubo un error inesperado"
var httpStatus = 0
return try {
println("Making http request in thread ${Thread.currentThread().name}")
val result = request.invoke()
httpStatus = result.code()
if (result.isSuccessful) {
return HttpResult.success(result.body(), result.code())
} else {
val errorResponse =
RESTClient.instance!!
.responseBodyConverter (JSONObject::class.java,
arrayOfNulls(0)).convert(result.errorBody() !!)
Log.e("REMOTE", errorResponse ? .toString() ? : "ERROR")
HttpResult.error(errorResponse ? .optString("ERROR", fallbackMessage) ?
: fallbackMessage, null, httpStatus)
}
} catch (e: Throwable) {
Log.e("REMOTE", "", e)
if (e is java.net.SocketTimeoutException) {
fallbackMessage = "No se completó la petición al servidor a tiempo"
}
HttpResult.error(fallbackMessage, e, httpStatus)
}
}
}
}

// dataService
interface Service {
@GET("/fake-uri")
suspend fun getVisitsAvailable(
@Path("userId") userId: Long
): Response 
}
Он был отлажен, функция, похоже, выполняется и завершает процесс правильно, ответ сервера правильный, данные отображаются в приложении правильно, но через некоторое время выдается исключение, и приложение полностью закрывается.
Библиотеки были обновлены, вот используемые в настоящее время версии.

Код: Выделить всё

plugins {
val kotlinVersion = "1.9.24"
id("com.android.application") version "8.1.3" apply false
id("org.jetbrains.kotlin.android") version kotlinVersion apply false
id("com.google.devtools.ksp") version "$kotlinVersion-1.0.20" apply false
id("com.google.gms.google-services") version "4.4.0" apply false
id("com.google.firebase.crashlytics") version "2.9.9"  apply false
}

Код: Выделить всё

dependencies {
val lifecycleVersion = "2.7.0"

implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.core:core-splashscreen:1.0.1")

//LifeCycle
implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycleVersion")
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion")
implementation("androidx.lifecycle:lifecycle-service:$lifecycleVersion")

//[START] Jetpack Compose
val navVersion = "2.7.7"

implementation("androidx.activity:activity-compose:1.9.0")
implementation(platform("androidx.compose:compose-bom:2024.05.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")

// Integration with ViewModels
implementation("androidx.lifecycle:lifecycle-runtime-compose:$lifecycleVersion")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycleVersion")

// Navigation between composables
implementation("androidx.navigation:navigation-compose:$navVersion")
//[END] Jetpack Compose

// alternative to shared preferences
implementation("androidx.datastore:datastore-preferences:1.1.1")

// Camera and scanner
val cameraxVersion = "1.3.3"
implementation("androidx.camera:camera-core:$cameraxVersion")
implementation("androidx.camera:camera-camera2:$cameraxVersion")
implementation("androidx.camera:camera-view:$cameraxVersion")
implementation("androidx.camera:camera-lifecycle:$cameraxVersion")
implementation("com.google.mlkit:barcode-scanning:17.2.0")

//Location
implementation("com.google.android.gms:play-services-location:21.2.0")

//Http client
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.11.0"))
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")

//Room
val roomVersion = "2.6.1"
implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")
ksp("androidx.room:room-compiler:$roomVersion")
implementation("androidx.room:room-ktx:$roomVersion")

//Firebase
implementation(platform("com.google.firebase:firebase-bom:33.0.0"))
implementation("com.google.firebase:firebase-storage")
implementation("com.google.firebase:firebase-crashlytics")
implementation("com.google.firebase:firebase-analytics")

//Google Maps
implementation("com.google.maps.android:maps-compose:4.3.0")
implementation("com.google.maps.android:android-maps-utils:3.4.0")

//[START] Testing Dependencies
testImplementation("junit:junit:4.13.2")
testImplementation("androidx.test:core:1.5.0")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2024.05.00"))
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
//[END] Testing Dependencies
}
Я ценю любую помощь, включая альтернативы для замены использования kotlin.coroutines или решения текущего использования, я безуспешно исследовал и тестировал около 2 дней.
Большое спасибо.


Подробнее здесь: https://stackoverflow.com/questions/785 ... all-an-api
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»