You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Repository的API调用方法编写通用函数以避免重复?

如何为Repository的API调用编写通用函数?

当然可以!你当前的两个方法存在大量重复的网络检查、异常捕获和结果判断逻辑,完全可以通过高阶函数封装通用逻辑,让代码更简洁、易维护。

解决方案:封装通用API调用函数

首先在你的Repository类中定义一个私有的通用suspend函数,把所有重复的逻辑都放在这里:

private suspend fun safeApiCall(apiCall: suspend () -> MyModel): MyResult {
    // 检查网络连接
    if (!util.checkDeviceInternet()) {
        return MyResult.Error(MyResult.ErrorType.NO_INTERNET)
    }

    return try {
        // 执行传入的API调用
        val apiResult = apiCall()
        // 判断API返回状态
        if (apiResult.status == "200") {
            MyResult.Content(apiResult)
        } else {
            MyResult.Error(MyResult.ErrorType.API_ERROR)
        }
    } catch (e: Exception) {
        // 捕获所有API调用异常
        MyResult.Error(MyResult.ErrorType.API_ERROR)
    }
}

简化原有方法

接下来,你只需要修改原来的两个方法,让它们调用这个通用函数即可:

override suspend fun getImageFromRemote(): MyResult {
    return safeApiCall { remoteInterface.getRandomImage() }
}

override suspend fun getImageByIdFromRemote(id: String): MyResult {
    return safeApiCall { remoteInterface.getRandomImageById(id) }
}

扩展说明

如果之后你的项目中新增其他返回MyModel类型的API接口,直接复用这个safeApiCall函数即可。要是需要支持不同的返回类型,可以把函数改成泛型版本,进一步提升通用性:

private suspend fun <T> safeApiCall(apiCall: suspend () -> T): MyResult where T : BaseModel {
    if (!util.checkDeviceInternet()) {
        return MyResult.Error(MyResult.ErrorType.NO_INTERNET)
    }

    return try {
        val apiResult = apiCall()
        if (apiResult.status == "200") {
            MyResult.Content(apiResult)
        } else {
            MyResult.Error(MyResult.ErrorType.API_ERROR)
        }
    } catch (e: Exception) {
        MyResult.Error(MyResult.ErrorType.API_ERROR)
    }
}

这里假设你有一个BaseModel基类,所有API返回模型都继承它并包含status字段。

这样的重构不仅减少了代码重复,还让后续的逻辑修改(比如调整错误类型、修改网络检查规则)变得更高效——只需要改动通用函数一处即可。

内容的提问来源于stack exchange,提问作者Ma2340

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:00:21