[Android] [改造]使用拦截器调用不同的API
我正在研究一个使用改造来处理网络呼叫的Android项目。我很难弄清楚用例。
我有一个API(API1),该API已经实现,并从多个地方称为。 现在,在调用API1之前,我需要调用新的API(API2)。
这样做最好的方法是什么?
我可以将拦截器用于此目的吗?拦截器是处理此用例的最佳方法吗?
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;
}
}
}
或者
fun suspend callApi1() {
return api2.execute()
.map { api2Response ->
if (api2Response.code() == 200) api1.execute()
else return null
}
}
我个人喜欢拦截器方法,我感到它很干净,但不确定是否将拦截器用于此目的。 应该使用哪些拦截器使用addinterceptor
或addnetWrokinterceptor
(在我的情况下,我可以将它们添加到其中任何一个?)
另外,我 项目,我不确定在拦截器中执行其他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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第二种方法更有利,因为使用拦截器会在拦截器内部遮蔽逻辑,而其他人都不会知道。此外,通常为单个单个服务创建了改造实例,该逻辑也应在业务组件中处理,因为API是数据层。
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.