Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Last active October 13, 2022 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yongjhih/cf5940d922e9964a601559d98a511d0c to your computer and use it in GitHub Desktop.
Save yongjhih/cf5940d922e9964a601559d98a511d0c to your computer and use it in GitHub Desktop.
Retrofit Annotation
class InterceptedInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response =
try {
val invocation = chain.request().tag<Invocation>()
val annotation = invocation?.method()?.annotation<Intercepted>()
(annotation?.value?.java?.constructors?.first()
?.newInstance(invocation.arguments()) as Interceptor?)?.intercept(chain)
} catch (e: Throwable) { null } ?: chain.proceed(chain.request())
}
@yongjhih
Copy link
Author

yongjhih commented Oct 13, 2022

class InterceptedRequestInterceptor(
        private val interceptors: Map<KClass<out RequestInterceptor>, RequestInterceptor> = emptyMap(),
) : RequestInterceptor {
    val cache: WeakHashMap<KClass<out RequestInterceptor>, RequestInterceptor?> by lazy { WeakHashMap() }

    override fun intercept(request: Request): Request =
            try {
                request.tag<Invocation>()?.method()?.annotation<RequestIntercepted>()?.value?.fold(request) { req, klass ->
                    try {
                        (interceptors[klass] ?: cache.getsOrPut(klass) {
                            klass.java.constructors.first()?.newInstance() as RequestInterceptor?
                        })?.intercept(req)
                    } catch (e: Throwable) { null } ?: req
                }
            } catch (e: Throwable) { null } ?: request
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment