1

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.

Ahmad Shahwaiz
  • 1,432
  • 1
  • 17
  • 35
  • 3
    Tagz ? Are you sure you it is not Tag (wihtout Z) ? – Sergiob Sep 02 '21 at 08:14
  • yeah I was using my custom, now im using without the Z. I think im able to see the tag in my interceptor, just looking it now how to parse it. – Ahmad Shahwaiz Sep 02 '21 at 09:09
  • request.tag(Invocation::class.java)?.let { cachePolicyType = it.arguments()[0] as CachePolicy.Type } I hope there is a better way to get that tag value. – Ahmad Shahwaiz Sep 02 '21 at 09:14

1 Answers1

2

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.

Ahmad Shahwaiz
  • 1,432
  • 1
  • 17
  • 35