【发布时间】:2019-06-02 07:22:07
【问题描述】:
第一次使用协程。需要帮助。
这是我的流程:
Presenter 想要登录所以调用 Repository Interface。 Repository 实现 RepositoryInterface。 所以 Repository 调用 APIInterface。 APIInterface 由 APIInterfaceImpl 实现。 APIInterfaceImpl 最终调用了 MyRetrofitInterface。
这是流程图:
Presenter -> Repository -> APIInterfaceImpl -> MyRetrofitInterface
收到登录响应后:
APIInterfaceImpl -> Repository -> 将数据存储在缓存中 -> 将 http 状态码提供给 Presenter
这是我的代码:
RepositoryInterface.kt
fun onUserLogin(loginRequest: LoginRequest): LoginResponse
Repository.kt
class Repository : RepositoryInterface {
private var apiInterface: APIInterface? = null
override fun onUserLogin(loginRequest: LoginRequest): LoginResponse {
return apiInterface?.makeLoginCall(loginRequest)
}
}
APIInterface.kt
suspend fun makeLoginCall(loginRequest): LoginResponse?
APIInterfaceImpl.kt
override suspend fun makeLoginCall(loginRequest: LoginRequest): LoginResponse? {
if (isInternetPresent(context)) {
try {
val response = MyRetrofitInterface?.loginRequest(loginRequest)?.await()
return response
} catch (e: Exception) {
//How do i return a status code here
}
} else {
//How do i return no internet here
return Exception(Constants.NO_INTERNET)
}
}
MyRetrofitInterface.kt
@POST("login/....")
fun loginRequest(@Body loginRequest: LoginRequest): Deferred<LoginResponse>?
我的问题是:
- 我的方法在架构上是否正确?
- 如何在我的代码中传递 http 错误代码或没有互联网连接
- 我的解决方案有更好的方法吗?
【问题讨论】:
-
在哪里以及如何启动协程?
-
是的,这就是我的问题...你能告诉我如何以及在哪里可以做到这一点吗?
标签: android kotlin kotlin-coroutines coroutine