2

I am working on an Android project which uses retrofit to handle network calls. I have a hard time figuring out a use case.

I have an API (api1) which has already been implemented and is being called from multiple places. Now, I need to call a new API (api2) before calling api1.

What would be the best way of doing this ?

Can I use interceptors for this purpose ? Are interceptors the best way to handle this use case ?

public class MyApi2Interceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {

    // original request
    Request request = chain.request();

    val api2Response = api2.execute()

    if (api2Response.code() == 200) {
        return chain.proceed(request);
    } else {
        return null;
    }
  }
}

Or

fun suspend callApi1() {
  return api2.execute()
         .map { api2Response -> 
            if (api2Response.code() == 200) api1.execute()
            else return null
         }
}

I personally like the interceptor approach I feel its clean, but not sure if interceptors are used for this purpose. Also which interceptors should I use addInterceptor or addNetwrokInterceptor (I guess in my case I can add them in any one of them ?)

I haven't actually tried out yet on my project and I am not sure if executing a different api in interceptor would actually work.

Please let me know your thoughts on this. Thanks in advance.

ik024
  • 3,566
  • 7
  • 38
  • 61
  • This may help you : [Retrofit 2 - Dynamic URL](https://stackoverflow.com/questions/32559333/retrofit-2-dynamic-url) – Mobile First Solutions Jun 14 '22 at 22:20
  • @ik024 - Were you able to achieve this use-case. I'm facing the same issue. API is not getting triggered from Interceptor. Is it possible? What was your outcome? – Abhijeet Mar 30 '23 at 18:22

1 Answers1

2

The second approach is more favorable as using interceptor would shadow the logic inside the interceptor and no one else would know about it. Also retrofit instances are usually created for single single service, this logic should be also handled in a business component as APIs are a data layer.

Filip Sollár
  • 91
  • 1
  • 5