广义函数以避免重复

Generalized function to avoid repeatativeness

我想为我的存储库方法创建一个通用函数来调用 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 个方法具有重复的函数体。有什么办法可以编写一个通用函数来实现与这两个函数相同的功能吗?

您可以删除 try{}catch{} 块并将其替换为 CoroutineExceptionHandler:

val coroutineExceptionHandler = CoroutineExceptionHandler{_,_ -> return MyResult.Error(MyResult.ErrorType.API_ERROR)
}

coroutineScope.launch(coroutineExceptionHandler ){
  val result = getImageFromRemote()
}

您可以使用内联函数来执行此操作,开销为零。

private inline fun usefulFunction(block: () -> MyModel): MyResult {
    if (util.checkDeviceInternet()) {
        try {
            val result = block()
            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 getImageFromRemote(): MyResult {
    return usefulFunction {
        remoteInterface.getRandomImage()
    } 
}

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