Search code examples
androidannotationsretrofit2okhttpretrofit2.6

In retrofit, how can I use Tag in the request as a parameter value without using Call?


Retrofit: I want to use Tag annotation to pass some data in the request, and then I would like to intercept that data from the interceptor.

Something like this

How can I use it something like this, but without using Call

@Target(AnnotationTarget.VALUE_PARAMETER,
        AnnotationTarget.FUNCTION
    )
    @Retention(AnnotationRetention.RUNTIME)
    annotation class Tagz

@GET
suspend fun getUsers(@Tagz value: CachePolicy.Type, @Url placeholder: String): Response<UserEntity?>

Using the above is throwing me this:

java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1)

How can I pass my value in the parameter as a tag in the request?

BTW: I was able to use tag like this

@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
    @Retention(AnnotationRetention.RUNTIME)
    annotation class CachePolicyTag(val value: CachePolicy.Type)

@GET
@CachePolicyTag(CachePolicy.Type.DefaultCache)
suspend fun getUsers(@Url placeholder: String): Response<UserEntity?>

But instead of an annotation function, I want it to pass as a parameter in this suspend function.


Solution

  • I used retrofit @TAG to pass tag value and intercepted in the okhttp interceptor.

    @GET
    suspend fun getUsers(@Tag cacheType: CachePolicy.Type, @Url placeholder: String): Response<UserEntity?>
    

    and in my Okhttp interceptor

    override fun intercept(chain: Interceptor.Chain): Response {
            val request =  chain.request() 
            val response = chain.proceed(request)
            request.tag(Invocation::class.java)?.let {
                    kotlin.runCatching {
                       val cachePolicyType = it.arguments()[0] as CachePolicy.Type
                    } 
            }
            return response
    }
    

    In case of any errors or class cast exception, it won't throw any exception out side of the runCatching block as well.