下面是我的代码:
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调用的逻辑,然后调用后片段。
回调接口的另一种选择是使用协程。要做到这一点,将其标记为挂起函数并使用await()
而不是enqueue()
。await()
调用必须封装在try/catch中以捕获失败条件(类似于enqueue()
中的onFailure
)。我把无网络条件移到了开头,这样你就不必在if块中嵌套所有的代码。
suspend fun getRandomComputerDetails(context: Context): RandomComputerApiResponse? {
if (!isNetworkAvailable(context)) {
// NO INTERNET CONNECTION
errorDialogHandler(context, R.string.dialog_error_no_internet_connection)
return null
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val service: RandomComputerApiService =
retrofit.create(RandomComputerApiService::class.java)
val response = try {
service.getRandomComputer().await()
} catch (t: Throwable) {
// code for failure condition
// errorDialogHandler(context, R.string.???)
Log.e("Response error", t.message.toString())
return null
}
if (response.isSuccessful) {
return response.body()
}
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")
}
}
return null
}
然后在你的片段中:
lifecycleScope.launch {
val response = getRandomComputerDetails(requireContext())
if (response != null) {
// Do something with response of type RandomComputerApiResponse
}
}
您可以创建接口并通过它返回结果。例如,我创建了一个ResultListener接口
interface ResultListener<S> {
fun onSuccess(successModel: S)
fun onFail(any: String?)
fun onError(e: Throwable?)
}
在response.isSuccessful
上使用resultListener.onSuccess(randomComputerList)
从接口获取结果
fun getRandomComputerDetails(context: Context, resultListener: ResultListener<RandomComputerApiResponse>) {
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?
resultListener.onSuccess(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)
}
}
调用这个有趣的
getRandomComputerDetails(
context = this,
resultListener = object : ResultListener<RandomComputerApiResponse> {
override fun onSuccess(successModel: RandomComputerApiResponse) {
//handle success result
}
override fun onFail(any: String?) {
//handle Fail result
}
override fun onError(e: Throwable?) {
//handle Error
}
})