Best Scope in Dagger2 for Okhttp3 with dynamic Interceptors

萝らか妹 提交于 2019-12-23 20:03:12

问题


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?

Thanks a lot!


回答1:


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

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

  • 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.


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

It would look something like this:

// 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();
}

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.



来源:https://stackoverflow.com/questions/37050348/best-scope-in-dagger2-for-okhttp3-with-dynamic-interceptors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!