在Ktor中使用kotlin进行泛型api调用 [英] Generic api calling using kotlin Reified in Ktor

查看:211
本文介绍了在Ktor中使用kotlin进行泛型api调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是KMM的新手,并尝试使用带有reified的ktor创建用于api调用的通用函数,它似乎可以在android上正常工作,但在iOS中引发错误这是我在共享文件中常见的api调用返回.

I am new to KMM and trying to create a generic function for api calling using ktor with reified and it seems to work fine with android but throws an error in iOS This is my common api call return in Shared file.

@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中效果很好:-

It works good in android if I call it like this :-

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

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

But I am not able to get it run on iOS devices it shows me error like this :-

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=}

在此方面的任何帮助都将受到赞赏.谢谢

Any help in this is appreciated. Thanks

推荐答案

好的,从Slack对话中进行吧这里很显然,由于 swift 不支持 reified ,因此无法创建此类通用函数.唯一的解决方案是,我们需要为所需的每个不同的api调用创建不同的函数.

Okay so from the Slack conversation here it's clear that it's not possible to create this type of generic function as swift doesn't support reified. The only solution is we need to create different functions for every different api call we need.

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

For eg :- we can create a interface inside which we have all the api implementation and use it in the native platforms. Like this :-

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

现在我们可以在本机平台上使用它了.

Now we can use this in our native platforms.

这篇关于在Ktor中使用kotlin进行泛型api调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆