java – 从Android Application类刷新Dagger 2实例

我在我的模块类中有一组@Singleton和@Provides方法,用于在整个应用程序中创建Singleton实例.一切都很好,除了几个瓶颈情况,如下所示:

步骤1.我正在从OKHttpClient创建一个带有Auth令牌的Retrofit实例,每次都进行经过身份验证的api调用(通过SharedPreferences处理Auth令牌检索和插入).但是,在我通过清除数据库和共享首选项值注销应用程序之后重新启动活动时,问题就开始了.

步骤2.注销后,我再次请求获取auth令牌并再次插入SharedPreferences以供将来使用.

第3步:现在如果我继续进行剩余的api调用,Dagger @Singleton和@Provides方法的前一个实例保持相同,除非我通过从最近的任务中清除它来重新启动应用程序. (新的身份验证令牌未更新)

需要修复:

>如何强制触发Dagger提供程序方法再次触发或撤消它?
>是否有任何方法可以像应用程序重新启动时那样刷新应用程序类数据.

请找到我项目中使用的Dagger 2架构:

NetworkModule.java(Dagger Module类)

@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组件类)

@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组件的类)

   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天里完全坚持了这一点.我无能为力,因为我的完整架构是建立在此之上的.请原谅我的拼写错误和更正.如果对此有任何澄清,请告诉我.提前致谢.

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?

不,没有这样的触发器.组件负责为您提供依赖项.如果您已完成一个组件并且想要使其无效(即您要再次创建依赖项),则必须从中处置它(null out)并创建一个新组件.现在将再次创建所有依赖项.

转载注明原文:java – 从Android Application类刷新Dagger 2实例 - 代码日志