也许这是一个非常简单的话题,但我找不到正确的答案。
这是交易,我正在使用以下逻辑将API处理到当前的android项目中:
SampleApi类
接口ISampleApi
接口SampleClient
GetUserData类
现在,我要搬到Kotlin,我无法将enqueue()
函数从改造过程复制到我的Api类中。这是我的代码的示例:
GetUserData.java:
class GetUserData {
private void tryGetData() {
sampleApi.getSomeData(userId, new Callback<Data>() {
@Override
public void onResponse(final Call<Data> call, final Response<Data> response) {
......Do Something
}
@Override
public void onFailure(final Call<Data> call, final Throwable t) {
......Do Something
}
});
我正在使用一个接口,以便将要实现的方法声明为API类:
public interface ISampleApi {
void getSomeData(@NonNull String userId,
@NonNull Callback<Data> callback);
}
这是我的API类:
public class SampleApi implements ISampleApi {
............
@Override
public void getSomeData(@NonNull final String userId,
@NonNull final Callback<Data> callback) {
myClient.getSomeData(userId).enqueue(callback);
}
}
这是使用翻新版的MyClient:
public interface SampleClient {
@GET("user/data/{userId}")
Call<Data> getSomeData(@NonNull @Path("userId") String userId);
}
上面的所有代码都可以正常工作,这就是我在应用程序中使用的毫无问题的
现在,这是转移到Kotlin时的问题,我尝试将enqueue回调创建到SampleApi中,我需要将响应返回到创建回调的类,在Kotlin中应该是这样的: / p>
fun getSomeData(userId: String, callback: CallBack<Data>) {
client?.getSomeData(userId).enqueue(callback)
}
但是,当尝试这样做时,Android Studio告诉我必须创建扩展功能,然后创建扩展功能,经过Android Studio的更多建议和一些研究后,结果是这样的:
override fun getSomeData(@NonNull userId: String,
@NonNull callback: Callback<Data>) {//Neve using this callback
client?.getSomeData(userId).enqueue {
success = {
success -> Do Something
}
failure = {
failure -> Do Something
}
}
}
fun<T> Call<T>.enqueue(callback: BaseCallback<T>.() -> Unit) {
val callbackBk = BaseCallback<T>()
callback.invoke(callbackBk)
this.enqueue(callbackBk)
}
class BaseCallback<T>: Callback<T> {
var success: ((Response<T>) -> Unit)? = null
var failure: ((t: Throwable?) -> Unit)? = null
override fun onFailure(call: Call<T>, t: Throwable) {
failure?.invoke(t)
}
override fun onResponse(call: Call<T>, response: Response<T>) {
success?.invoke(response)
}
}
BaseCallback.kt
open class BaseCallback<T: Validatable>(): Callback<BaseResponseBody<T>> {
var success: ((T) -> Unit)? = null
var failure: ((networkingError: NetworkingError?) -> Unit)? = null
override fun onResponse(call: Call<BaseResponseBody<T>>, response: Response<BaseResponseBody<T>>) {
if (response?.code() != null
&& response.isSuccessful
&& response.body() != null
&& response.body().containsValidSuccess()) run {
onSuccessfulResponse(response.body().data!!)
} else if (response != null
&& response.isSuccessful
&& response.body() != null) {
onSuccessfulResponse()
} else {
onNonSessionErrorEncountered(networkingError)
}
}
override fun onFailure(call: Call<BaseResponseBody<T>>, throwable: Throwable) {
onNonSessionErrorEncountered(NetworkStateError(throwable))
}
@VisibleForTesting(otherwise = PROTECTED)
fun onSuccessfulResponse(responseValue: T) {
success?.invoke(responseValue)
}
@VisibleForTesting(otherwise = PROTECTED)
fun onSuccessfulResponse() {
// This method intentionally left blank.
}
fun onSessionErrorEncountered() {
// This method intentionally left blank.
}
@VisibleForTesting(otherwise = PROTECTED)
fun onNonSessionErrorEncountered(networkingError: NetworkingError) {
failure?.invoke(networkingError)
}
}
此代码在这里工作正常,我可以接收数据,但是我需要在调用此终结点的类内接收响应,因为我需要更改UI。
我真的非常感谢您的帮助,我已经坚持了一段时间,我需要解决该问题才能继续使用该应用程序。
答案 0 :(得分:0)
将以下代码放入AppRepository.kt文件中
companion object {
fun getServiceDetails(map: Map<String, String>, callback: ApiCallback<ServiceDetailsDataClass.ServiceDetailsResponse>) {
val retrofit = ApiClient.retrofit
val callGet = retrofit?.create<ApiService.ServiceDetails>(ApiService.ServiceDetails::class.java)?.getServiceDetails(map, ApiConstants.API_KEY, ApiConstants.API_LANG)
callGet?.enqueue(object : Callback<ServiceDetailsDataClass.ServiceDetailsResponse> {
override fun onFailure(call: Call<ServiceDetailsDataClass.ServiceDetailsResponse>?, t: Throwable?) {
callback.onError(t.toString())
}
override fun onResponse(call: Call<ServiceDetailsDataClass.ServiceDetailsResponse>?, response: Response<ServiceDetailsDataClass.ServiceDetailsResponse>?) {
if (response?.isSuccessful!!) {
callback.onSuccess(response.body()!!)
} else {
setError(callback, response)
}
}
})
}
ApiCallBack.kt接口文件具有代码:
interface ApiCallback<T> {
fun onException(error: Throwable)
fun onError(error: String)
fun onSuccess(t: T)
}
ApiService.kt文件具有代码:
interface ApiService {
interface ServiceDetails {
@GET("api/path/here/")
fun getServiceDetails(@QueryMap map: Map<String, String>, @Header(ApiConstants.KEY_X_API) apiKey: String, @Header(ApiConstants.KEY_ACCEPT_LANGUAGE) language: String): Call<ServiceDetailsDataClass.ServiceDetailsResponse>
}
现在使用调用api:
AppRepository.getServiceDetails(map, object : ApiCallback<ServiceDetailsDataClass.ServiceDetailsResponse> {
override fun onException(error: Throwable) {
serviceDetailsResponse.value = error
}
override fun onError(error: String) {
serviceDetailsResponse.value = error
}
override fun onSuccess(t: ServiceDetailsDataClass.ServiceDetailsResponse) {
serviceDetailsResponse.value = t
}
})
希望它对您有帮助。