从 Android Application 类刷新 Dagger 2 实例 [英] Refreshing Dagger 2 instance from Android Application class
问题描述
我的模块类中有一组 @Singleton
和 @Provides
方法,目的是在整个应用程序中创建 Singleton 实例.除了少数瓶颈情况外,一切正常,如下所示:
I have a set of @Singleton
and @Provides
method in my module class for the purpose of creating Singleton instance throughout the application. Everything works fine except few bottle neck scenarios like as follows:
第 1 步.我正在从 OKHttpClient
创建一个带有 Auth 令牌的 Retrofit 实例,以便每次都进行经过身份验证的 api 调用(Auth 令牌检索和插入通过 SharedPreferences
).但是,当我通过清除数据库和共享首选项值注销应用程序后重新启动活动时,问题就开始了.
STEP 1. I am creating a Retrofit instance from OKHttpClient
with Auth token in it to make a authenticated api calls each time (Auth token retrieval and insertion is handled through SharedPreferences
). But the problem starts at the time of relaunching the activity after when i logout the application by clearing databases and shared preferences values.
第 2 步.注销后,我再次请求获取身份验证令牌并再次插入 SharedPreferences
以备将来使用.
STEP 2. After logout, am making an another request to fetch auth tokens and inserting into SharedPreferences
again for future use.
第 3 步:现在,如果我继续其余的 api 调用,Dagger @Singleton
和 @Provides
方法的前一个实例保持不变,除非并且直到我通过从最近的任务中清除它来重新启动应用程序.(新的授权令牌未更新)
STEP 3: Now if i proceed with the rest of api calls, the previous instance of the Dagger @Singleton
and @Provides
method remains same unless and until if i relaunch the app by clearing it from the recent task. (New auth token is not updated)
需要修复:
如何强制触发Dagger提供者方法再次触发或撤销?
How to trigger the Dagger provider methods forcibly to trigger or revoke it again?
是否有任何方法可以像重新启动应用程序时一样刷新应用程序类数据?
Is there any method to refresh the application class data as similar behaviour like when the app relaunches.?
请找到我的项目中使用的 Dagger 2 架构:
Please find my Dagger 2 architecture used in my project:
NetworkModule.java(Dagger 模块类)
NetworkModule.java (Dagger Module class)
@Module
public class NetworkModule {
private Context context;
public NetworkModule(Application app) {
this.context = app;
}
@Provides
@Named("network.context")
Context providesContext() {
return context;
}
@Singleton
@Provides
OkHttpClient providesOkHttpClient(@Named("network.context")final Context context) {
final UserProfile userProfile = GsonUtils.createPojo(SharedPrefsUtils.getString(Constants.SHARED_PREFS.USERS_PROFILE, "",context), UserProfile.class);
Logger.i(userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "----OAuth token empty---");
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("Api-Version", "application/vnd.addo-v1+json")
.header("Access-Token", userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "")
.header("App-Version", Utils.getVersionName(context))
.header("Device-Platform","android")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
return httpClient.build();
}
@Provides
@Named(Constants.INJECTION.BASE_URL)
String providebaseURL() {
return Constants.URL.BASE_URL;
}
@Singleton
@Provides
Retrofit providesRetrofit(@Named("network.context")Context context, @Named(Constants.INJECTION.BASE_URL) String baseURL, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
@Singleton
@Provides
NetworkApiService providesNetworkApiService(Retrofit retrofit){
return retrofit.create(NetworkApiService.class);
}
@Singleton
@Provides
ProjectPresenter providesProjectPresenter(NetworkApiService networkApiService){
return new ProjectPresenterImpl(networkApiService);
}
}
AppComponent.java(Dagger 组件类)
AppComponent.java (Dagger component class)
@Singleton
@Component(modules = {NetworkModule.class})
public interface AppComponent {
//ACtivity
void inject(AuthenticationActivity authenticationActivity);
void inject(MainActivity mainActivity);
//Fragments
void inject(ProjectsListFragment projectsListFragment);
}
Application.java(用于创建 Dagger 组件的类)
Application.java (Class used to create Dagger component)
public class Application extends Application {
private AppComponent appComponent ;
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
ButterKnife.setDebug(BuildConfig.DEBUG);
appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).networkModule(new NetworkModule(this)).build();
}
public AppComponent getAppComponent() {
return appComponent;
}
}
请提供您的建议或技巧来帮助我解决 Dagger 2 的这种奇怪行为.任何类型的解决方案都会对我有很大帮助,因为在过去的 6 天里我完全陷入困境.我无能为力和困惑,因为我的完整架构是建立在此之上的.请原谅我的错别字和更正.如果需要对此进行任何澄清,请 Ping 我.提前致谢.
Kindly help me with your suggestions or tips to resolve this weird behaviour of Dagger 2. Any kind of solutions will be much helpful to me since I am completely stuck up with this for the past 6 days. I am clueless and perplexed because my complete architecture is built on top of this. Please forgive me for typos and corrections. Ping me if there are any clarifications required regarding the same. Thanks in advance.
推荐答案
如何强制触发Dagger provider方法再次触发或撤销?
How to trigger the Dagger provider methods forcibly to trigger or revoke it again?
是否有任何方法可以像重新启动应用程序时一样刷新应用程序类数据?
Is there any method to refresh the application class data as similar behaviour like when the app relaunches?
不,没有这样的触发器.Component
负责为您提供依赖项.如果你完成了一个 Component
并且你想让它失效(即你的依赖被再次创建)你必须从中处理它(null out)并创建一个新的 Component
.现在将再次创建您的所有依赖项.
Nope, there isn't such a trigger. Component
is responsible for providing you a dependency. If you are done with one Component
and you want to invalidate it (i.e. your dependencies to be created again) you have to dispose from it (null out) and create a new Component
. Now all your dependencies will be created again.
这篇关于从 Android Application 类刷新 Dagger 2 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!