在Ktor中使用kotlin Reified的通用api调用



我是KMM的新手,正在尝试创建一个通用函数,用于使用带有具体化的ktor的api调用,它似乎在android中运行良好,但在iOS中出现了错误这是我在共享文件中常见的api调用返回。

@Throws(Exception::class)
suspend inline fun<reified T> post(url: String, requestBody: HashMap<String, Any>?) : Either<CustomException, T> {
try {
val response = httpClient.post<T> {
url(BASE_URL.plus(url))
contentType(ContentType.Any)
if (requestBody != null) {
body = requestBody
}
headers.remove("Content-Type")
headers {
append("Content-Type", "application/json")
append("Accept", "application/json")
append("Time-Zone", "+05:30")
append("App-Version", "1.0.0(0)")
append("Device-Type", "0")
}
}
return Success(response)
}  catch(e: Exception) {
return Failure(e as CustomException)
}
}

如果我这样称呼它,它在android中效果很好:-

api.post<MyDataClassHere>(url = "url", getBody()).fold(
{
handleError(it)
},
{
Log.d("Success", it.toString())
}
)

但我无法在iOS设备上运行它,它向我显示了这样的错误:-

some : Error Domain=KotlinException Code=0 "unsupported call of reified inlined function `com.example.myapplication.shared.apicalls.SpaceXApi.post`" UserInfo={NSLocalizedDescription=unsupported call of reified inlined function `com.example.myapplication.shared.apicalls.SpaceXApi.post`, KotlinException=kotlin.IllegalStateException: unsupported call of reified inlined function `com.example.myapplication.shared.apicalls.SpaceXApi.post`, KotlinExceptionOrigin=}

如有任何帮助,我们将不胜感激。感谢

好的,从这里的Slack对话中可以清楚地看出,由于swift不支持reified,因此不可能创建这种类型的泛型函数。唯一的解决方案是,我们需要为我们需要的每个不同的api调用创建不同的函数。

例如:-我们可以创建一个接口,其中包含所有的api实现,并在本地平台中使用它。像这样:-

interface ApiClient {
suspend fun logIn(…): …
suspend fun createBlogPost(…): …
// etc
}

现在我们可以在我们的原生平台中使用它。

最新更新