【发布时间】:2023-04-01 01:33:02
【问题描述】:
我想为我的存储库方法提供一个通用函数,用于进行 API 调用。这是代码-
RemoteInterface.java
interface RemoteInterface {
@GET("...")
suspend fun getRandomImage(): MyModel
@GET(".../{id}/...")
suspend fun getRandomImageById(@Path("id") id: String): MyModel
}
现在我的 Repositoryclass 看起来像这样 -
override suspend fun getImageFromRemote(): MyResult {
if (util.checkDeviceInternet()) {
try {
val result = remoteInterface.getRandomImage()
if (result.status == "200") {
return MyResult.Content(result)
} else {
return MyResult.Error(MyResult.ErrorType.API_ERROR)
}
} catch (e: Exception) {
return MyResult.Error(MyResult.ErrorType.API_ERROR)
}
} else {
return MyResult.Error(MyResult.ErrorType.NO_INTERNET)
}
}
override suspend fun getImageByIdFromRemote(id: String): MyResult {
if (util.checkDeviceInternet()) {
try {
val result = remoteInterface.getRandomImageById(id)
if (result.status == "200") {
return MyResult.Content(result)
} else {
return MyResult.Error(MyResult.ErrorType.API_ERROR)
}
} catch (e: Exception) {
return MyResult.Error(MyResult.ErrorType.API_ERROR)
}
} else {
return MyResult.Error(MyResult.ErrorType.NO_INTERNET)
}
}
如您所见,我在 Repository 中的 2 个方法具有重复的函数体。有什么办法可以编写一个与这两个函数具有相同功能的通用函数?
【问题讨论】:
-
您必须使用
method overloading技术来实现这一点,请参见此处:medium.com/coding-blocks/… -
这不是你实施改造的方式。
-
@KaushikBurkule 你能解释一下我的错误吗?会有帮助的
-
让我确认您是否使用改造库进行网络调用?
-
是的,我愿意...我使用的是 2.6.1 版本
标签: android kotlin retrofit2 kotlin-coroutines