【问题标题】:Generic api calling using kotlin Reified in Ktor在 Ktor 中使用 kotlin Reified 进行通用 api 调用
【发布时间】:2021-03-29 04:45:10
【问题描述】:

我是 KMM 的新手,正在尝试使用带有 reified 的 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=}

对此的任何帮助表示赞赏。谢谢

【问题讨论】:

    标签: android ios generics kotlin-multiplatform ktor


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      相关资源
      最近更新 更多