Nothing frustrating than a bad design api, what if you have such api
{
status : "Success",
message : "",
x : {},
y:10
}
as the sample above x can be changed from api to another and some time there is other key along side.
what I want to say every response has status and message but we don't know what it has alongside with it, that task here is to know that if the response came with success or failed,
you can deserialize each response to its object and then check
xResponse.success = "Success"
for each type, that bad and I dont want to do that each time,
I want
xResposne.isSuccess()
there is two solution:
first one is base class and make every response class extend it
open class BaseResponse {
@SerializedName("Status")
val status: String = "Failures"
@SerializedName("Message")
val message: String = ""
}
fun BaseResponse.isSuccessful(): Boolean {
if (status == "Success") {
return true
}
return false
}
and then
data class ArticlesResponse(
@SerializedName("news")
val news: ArrayList<New>,
@SerializedName("pageCount")
val pageCount: Int,
):BaseResponse()
I don't like this solution because every new response class has to extend this base response, this extra for every response.
solution number two is reflection, because we know that every response class has a status property we can use that knowledge to create method that do reflection.
don't forget to add the reflection library
implementation "org.jetbrains.kotlin:kotlin-reflect:1.6.21"
then the actual work
fun Any.isSuccess(): Boolean {
val clazz = this.javaClass.kotlin
clazz.memberProperties.forEach {
if (it.name == "status") {
val status = it.get(this)
return status == "Success"
}
}
return false
}
and that is it, the problem with this solution is you get isSuccess() extension method on every class
Top comments (0)