4/27/2018 - 6:04 AM

Unwrapping converter class

Unwrapping converter class for getting the unwrapped part from received JSON only if api request had @UseOriginalResponse annotation on it

class MyUnwrappingConverterFactory : Converter.Factory() {

    override fun responseBodyConverter(type: Type?, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, *>? {
        // check if caller api contains our custom annotation                                                                                 
        for (annotation in annotations!!) {
            if (annotation is UseOriginalResponse) {
                // null here says that I, MyUnwrappingConverterFactory can't handle the response
                // so, I pass it on to next converter
                return null

        val envelopedType = TypeToken.getParameterized(APIResult::class.java, type!!).type

        val delegate = retrofit!!.nextResponseBodyConverter<APIResult<*>>(this, envelopedType, annotations)

        return Converter<ResponseBody, Any> { value ->
            //  return data variable from wrapper
            val wrapper: APIResult<*> = delegate.convert(value)
            // do some fancy stuff like saving the timestamp                                 
            // return unwrapped part
            return@Converter wrapper.data