我正在尝试使用View / ViewModel / UseCase / Repository模式进行基本网络调用。主要的异步调用是通过Coroutines执行的,它们都是使用Dispatchers.IO
启动的。
首先,这是相关的代码:
视图模型:
class ContactHistoryViewModel @Inject constructor(private val useCase: GetContactHistory) : BaseViewModel() {
// ...
fun getContactHistory(userId: Long, contactId: Long) {
useCase(GetContactHistory.Params(userId, contactId)) { it.either(::onFailure, ::onSuccess) }
}
}
GetContact历史使用案例:
class GetContactHistory @Inject constructor(private val repository: ContactRepository) : UseCase<ContactHistory, GetContactHistory.Params>() {
override suspend fun run(params: Params) = repository.getContactHistory(params.userId, params.contactId)
data class Params(val userId: Long, val contactId: Long)
}
上面使用的Base UseCase类:
abstract class UseCase<out Type, in Params> where Type : Any {
abstract suspend fun run(params: Params): Either<Failure, Type>
operator fun invoke(params: Params, onResult: (Either<Failure, Type>) -> Unit = {}) {
val job = GlobalScope.async(Dispatchers.IO) { run(params) }
GlobalScope.launch(Dispatchers.IO) { onResult(job.await()) }
}
}
最后,存储库:
class ContactDataRepository(...) : SyncableDataRepository<ContactDetailDomainModel>(cloudStore.get(), localStore),
ContactRepository {
override fun getContactHistory(userId: Long, contactId: Long): Either<Failure, ContactHistory> {
return request(cloudStore.get().getContactHistory(userId, contactId), {it}, ContactHistory(null, null))
}
/**
* Executes the request.
* @param call the API call to execute.
* @param transform a function to transform the response.
* @param default the value returned by default.
*/
private fun <T, R> request(call: Call<T>, transform: (T) -> R, default: T): Either<Failure, R> {
return try {
val response = call.execute()
when (response.isSuccessful) {
true -> Either.Right(transform((response.body() ?: default)))
false -> Either.Left(Failure.GenericFailure())
}
} catch (exception: Throwable) {
Either.Left(Failure.GenericFailure())
}
}
}
简介:在存储库中的catch{}
块中放置调试断点(直接在上面看到)显示正在抛出android.os.NetworkOnMainThreadException
。这很奇怪,因为两个协同程序都是使用Dispatchers.IO
的上下文启动的,而不是Dispatchers.Main
(Android的主要UI线程)。
问题:为什么抛出上述异常,如何更正此代码?
标记函数suspend
不会使其可挂起,您必须确保工作实际发生在后台线程中。
你有这个
override suspend fun run(params: Params) = repository.getContactHistory(params.userId, params.contactId)
这称之为
override fun getContactHistory(userId: Long, contactId: Long): Either<Failure, ContactHistory> {
return request(cloudStore.get().getContactHistory(userId, contactId), {it}, ContactHistory(null, null))
}
这些都是同步的,你的suspend
修饰符在这里没有做任何事情。
快速解决方法是像这样更改您的存储库
override suspend fun getContactHistory(userId: Long, contactId: Long): Either<Failure, ContactHistory> {
return withContext(Dispatchers.IO) {
request(cloudStore.get().getContactHistory(userId, contactId), {it}, ContactHistory(null, null))
}
}
但更好的解决方案是使用Coroutine适配器进行Retrofit。
问题是你不是在任何地方创建一个协同程序。您可以使用更高阶函数suspendCoroutine
。一个简单的例子是这样的:
private suspend fun <T, R> request(call: Call<T>, transform: (T) -> R, default: T): Either<Failure, R> {
return suspendCoroutine { continuation ->
continuation.resume(try {
val response = call.execute()
when (response.isSuccessful) {
true -> Either.Right(transform((response.body() ?: default)))
false -> Either.Left(Failure.GenericFailure())
}
} catch (exception: Throwable) {
Either.Left(Failure.GenericFailure())
})
}
}
你也可以通过很多方式来解决这个问题。请注意,此函数永远不会抛出异常。我认为这是有意的,但是如果你想向上传播以便能够将它包装在try-catch
块中,你可以使用continuation.resumeWithException(...)
。
由于此函数返回实际的协同程序,因此您的withContext(Dispatchers.IO)
应按预期工作。希望有所帮助!