简体   繁体   中英

[Android][Retrofit] Using interceptor to call different API

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM