我对DI一般很陌生,特别是Dagger。我目前有这个问题,我还没有设法找到解决方案。比方说,我有一个AppModule
为用户提供访问令牌放入请求头现在模块中的匕首2更新对象
@Module
public class AppModule {
@Provides
@Singleton
SharedPref provideSharedPreferences(Application application) {
return new SharedPref(application);
}
@Provides
@Singleton
AuthInterceptor provideAuthenticationInterceptor(SharedPref sharedPref) {
return new AuthInterceptor(sharedPref.getAccessToken());
}
@Provides
@Singleton
OkHttpClient provideHttpClient(AuthInterceptor authInterceptor) {
return new OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.build();
}
@Provides
@Singleton
DribbbleApi provideClient(OkHttpClient client, Gson gson) {
return new Retrofit.Builder()
.baseUrl(DribbbleApi.ENDPOINT)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
.create((DribbbleApi.class));
}
}
当用户第一次使用该应用程序的改型客户端,访问令牌不SharedPreference
存在,所以我为他们提供一个默认一。但是一旦他们登录,访问令牌将被保存到SharedPreference
,但我无法更新OkHttpClient
以接受新值,因为AuthInterceptor
已使用应用程序开始时的默认访问令牌创建。
我在看一些问题在这里有同样的问题,但似乎没有在我的情况下工作。我想有这个模块:
public class AuthenticationManager {
private String accessToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String ac) {
this.accessToken = ac;
}
}
@Module
public class AuthenticationModule {
@Provides
@Singleton
AuthenticationManager provideAuthenticationManager() {
return new AuthenticationManager();
}
}
和刚刚获得访问令牌和动态创建的改造/ OkHttp客户端,但这似乎不是我的权利。任何人都有解决方案?
非常详细的答案,谢谢!我说“AuthenticationManager”解决方案看起来不正确的原因是因为它增加了应用程序的复杂性。比方说,我有一堆4个活动,用户可以在任何活动中登录。现在,当他们在堆栈顶部登录时,他们回去时,我必须检查'AuthenticationManager'并在必要时重新创建Retrofit/OkHttp的另一个实例。不幸的是,这太复杂了,如果做得不对,可能会带来更多麻烦。这就是为什么我正在寻找一种解决方案,我可以为客户使用单例。 –