【发布时间】:2021-11-21 06:37:28
【问题描述】:
这是我的代码:
fun getRandomComputerDetails(context: Context) {
if (isNetworkAvailable(context)) {
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val service: RandomComputerApiService =
retrofit.create(RandomComputerApiService::class.java)
val listCall: Call<RandomComputerApiResponse> = service.getRandomComputer()
listCall.enqueue(object : Callback<RandomComputerApiResponse> {
override fun onResponse(
call: Call<RandomComputerApiResponse>,
response: Response<RandomComputerApiResponse>
) {
if (response.isSuccessful) {
val randomComputerList: RandomComputerApiResponse? = response.body()
if (randomComputerList != null) {
// TODO how to return randomComputerList?
}
Log.i("Response result", "$randomComputerList")
} else {
when (response.code()) {
400 -> {
errorDialogHandler(context, R.string.dialog_error_400)
Log.e("Error 400", "Bad Connection")
}
404 -> {
errorDialogHandler(context, R.string.dialog_error_404)
Log.e("Error 404", "Not Found")
}
500 -> {
errorDialogHandler(context, R.string.dialog_error_500)
Log.e("Error 500", "Server Error")
}
else -> {
errorDialogHandler(context, R.string.dialog_error_generic_error)
Log.e("Error", "Generic Error")
}
}
}
}
override fun onFailure(call: Call<RandomComputerApiResponse>, t: Throwable) {
Log.e("Response error", t.message.toString())
}
})
} else {
// NO INTERNET CONNECTION
errorDialogHandler(context, R.string.dialog_error_no_internet_connection)
}
}
如何返回我的randomComputerList 正文以便在片段中使用它?我正在使用retrofit2,我的想法是在特定文件中分离负责执行API调用逻辑的函数,然后在片段中调用它。
【问题讨论】:
-
这段代码到底是在哪里写的?在片段中,视图模型?
-
一个简单的 kotlin 文件,在一个单独的文件夹中。我做错了吗?我仍然没有改造经验,但我想简化代码并且不想将所有内容放在一个文件中。所以我不知道如何从函数中获取响应体
标签: android kotlin retrofit retrofit2