使用 Kotlin 在 Ktor 中具体化的通用 api 调用

Generic api calling using kotlin Reified in Ktor

我是 KMM 的新手,正在尝试为 api 调用创建一个通用函数,使用 ktor 和 reified,它似乎在 android 上工作正常,但在 iOS 中抛出错误 这是我在共享文件中的常用 api 调用 return。

@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 对话中可以看出 here 很明显无法创建此类通用函数,因为 swift 不支持 reified。唯一的解决方案是我们需要为我们需要的每个不同的 api 调用创建不同的函数。

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

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

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