【发布时间】:2021-05-15 11:38:14
【问题描述】:
我正在尝试使用 Ktor 为我们的 ApiServices 构建 KMM 应用程序。我创建了一个BaseApiClass,其中包含所有与 api 相关的代码。
BaseApiClass 的代码:-
class BaseAPIClass {
//Create Http Client
private val httpClient by lazy {
HttpClient {
defaultRequest {
host = ApiEndPoints.Base.url
contentType(ContentType.Application.Json)
header(CONNECTION, CLOSE)
}
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.ALL
}
install(HttpTimeout) {
requestTimeoutMillis = NETWORK_REQUEST_TIMEOUT
}
expectSuccess = false
// JSON Deserializer
install(JsonFeature) {
val json = Json {
ignoreUnknownKeys = true
coerceInputValues = true
}
serializer = KotlinxSerializer(json)
}
}
}
// Api Calling Functions I have few more similar to this but issue is random and comes in any of the api
@Throws(Exception::class)
suspend fun sampleApi(requestBody: RequestBody?) : Either<CustomException, BaseResponse<EmptyResponseModel>> {
return try {
val response = httpClient.post<BaseResponse<EmptyResponseModel>> {
url(ApiEndPoints.sample.url)
if (requestBody != null) {
body = requestBody
}
}
Success(response)
}
catch (e: Exception) {
Failure(e as CustomException)
}
}
这是我从 iOS 应用程序调用 api 的方式:-
val apiClass = BaseApiClass()
func callApi() {
apiClass.sampleApi(requestBody: .init(string: "value here")) { (result, error) in
result?.fold(failed: { (error) -> Any? in
// Error here
}, succeeded: { (result) -> Any? in
// Success here
})
}
}
现在在这里,如果我尝试使用相同的 object 即 apiClass 调用类似的更多 api,那么在几次调用之后它就会卡在我的函数 callApi 中,它甚至不会发送 api 请求(因为我可以'看不到打印在我的控制台中的请求日志),因此我无法执行任何其他操作,因为我没有从 api 获得任何东西。
只要我更改屏幕或关闭应用程序并尝试调用相同的 api,它就可以正常工作。
但是,如果我尝试使用BaseApiClass().sampleApi(request params here) {// completion handler here},而不是像 apiClass = BaseApiClass() 那样只创建一个对象,它可以正常工作,我对此没有任何问题。
我不确定是什么导致了这种情况发生在Android 中一切正常,只有iOS 面临这种情况。
【问题讨论】:
-
这似乎是一个错误,可能值得在youtrack.jetbrains.com/issues/KTOR 提出问题。另外,考虑附加一个项目来重现错误。
标签: ios swift kotlin-multiplatform ktor kotlin-multiplatform-mobile