Reputation: 15726
I use extension function to extend retrofit2.Response
object:
Snippet:
public class ErrorResponse {
private int code;
private String message;
private Response response;
}
import okhttp3.MediaType
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.ResponseBody
import retrofit2.Response
fun Response<*>.errorResponse(): ErrorResponse {
val errorResponse = ErrorUtils.parseError(this)
return errorResponse
}
And here use:
viewModelScope.launch(Dispatchers.Main) {
val response: Response<*> = TransportService.getTraidersList()
if (response.isSuccessful) {
finishLoadData()
val traders: List<Trader> = response.body() as List<Trader>
traderListLiveData.postValue(traders)
} else {
val errorResponse = response.errorResponse()
val message = errorResponse.message // here use extension function
messageLiveData.value = SingleEvent(message)
}
}
Nice. It's work fine.
But I want to use extension properties. I try this:
val Response<*>.errorResponse: ErrorResponse {
get() = ErrorUtils.parseError(this)
}
But I get compile error:
Function declaration must have a name Unresolved reference: get
Upvotes: 0
Views: 940
Reputation: 87
You don't need brackets for properties. It may look like this:
val Response<*>.errorResponse: ErrorResponse
get() = ErrorUtils.parseError(this)
Upvotes: 1