具有动态拦截器的Okhttp3在Dagger2中的最佳范围 [英] Best Scope in Dagger2 for Okhttp3 with dynamic Interceptors

查看:196
本文介绍了具有动态拦截器的Okhttp3在Dagger2中的最佳范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该范围如何与Auth令牌一起使用?在添加可以使用我的auth令牌对其进行签名的拦截器之前,我无法创建Retrofit实例.因此,我想在auth令牌可用时(登录后)创建Retrofit.在这种情况下如何使示波器正常工作?

How would the scope work with Auth Tokens? I cannot create my Retrofit instance until I can add an interceptor that signs it with my auth token. Therefore, I would like to create Retrofit when the auth tokens are available (after sign-in). How do I get scope working correctly in this situation?

非常感谢!

推荐答案

没有最好的方法,它也可能取决于您更改/重新创建Retrofit实例的频率

There is no best way of doing this, and it might also depend on how often you change / recreate your Retrofit instances.

哪个更好,或更哪个更适合您的用例,在很大程度上取决于您要完成的工作以及如何完成.尝试实现目标的方式有很多种,但总的来说,您有2种选择

What's better, or which better fits your use case depends very strongly on what you are trying to accomplish and how. There's many ways how what you are trying to achieve is possible, but in general you have 2 options

  • 为每个改造实例创建一个新客户端(例如,如果您仅登录一次用户),则只需在相同范围内添加客户端
  • 创建okhttp3的@Singleton实例,并在需要时使用newBuilder()
  • 修改客户端
  • Create a new client for every retrofit instance (e.g. if you just log the user in once), so you would just add the client within the same scope
  • Create a @Singleton instance of okhttp3 and modify the client when required by using the newBuilder()

我认为第一点是不言而喻的,只是在创建改造时创建客户,使用相同的作用域并完成.

I think the first point is self explanatory, just create your client when you create retrofit, use the same scope and be done.

第二种方法使用newBuilder()方法的Okhttp3功能,方法是在创建改造实例时将拦截器添加到okhttp客户端.

The second approach uses Okhttp3 feature of the newBuilder() method, by adding your interceptor to the okhttp client when creating your retrofit instance.

它看起来像这样:

// Some singleton client to maybe also use in other parts of your app
@Singleton
OkHttpClient provideClient() { return new OkHttpClient(); }

// creating your retrofit client
@UserScope
Retrofit provideRetrofit(OkHtpClient client, Interceptor userInterceptor) {
    return new Retrofit.Builder()
            .client(client.newBuilder() // new builder to modify okhttp3
                .addNetworkInterceptor(interceptor)
                .build())
            /* other settings */
            .build();
}


如果您有创造力,也可以只在拦截器上公开一个setCredentials()方法,则只需创建一次即可,然后通过将它们添加到@Singleton范围来重用所有对象.然后,您可以通过访问和修改拦截器来更改用户,尽管按照我的愚见,这不是一个干净的方法.


If you get creative you can also just expose a setCredentials() method on your interceptor, then you can just create them once and reuse all the objects by adding them to the @Singleton scope. You'd then change your user by accessing and modifying your interceptor, albeit this is not a clean approach in my humble opinion.

这篇关于具有动态拦截器的Okhttp3在Dagger2中的最佳范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆