我可以更新ApplicationModule并在每次注射时获得更新的值

时间:2016-09-05 09:13:57

标签: java android dependency-injection dagger-2

我可以更改Application module中存储的值并将其恢复到新活动或其他位置吗?我已经尝试过这段代码了,我希望@Provides带注释的方法每次调用都会调用DaggerExampleBuilder.builde().appComponent(...).build().inject()

以下是我的ApplicationModule代码:

 @Module
public class ApplicationModule {
    private HandsFreeApp app;
    private Property currentProperty;

public ApplicationModule(HandsFreeApp app) {
    this.app = app;
    Log.d("myTag", "ApplicationModule: "+hashCode());
}

@Provides @Singleton Context provideAppContext() {
    return app;
}

@Provides @Singleton RestClient provideRestClient(Realm realm) {
    TokenDataStore tokenDataStore = new TokenDataStore(realm);
    GetTokenUseCase tokenUseCase = new GetTokenUseCase(new TokenRepository(tokenDataStore));
    return new RestClientRetrofit(tokenUseCase);
}

@Provides @Singleton Realm provideRealm() {
    Realm.setDefaultConfiguration(new RealmConfiguration.Builder(app).build());
    return Realm.getDefaultInstance();
}

@Provides @Singleton Property getCurrentProperty(Realm realm) {

    if(currentProperty == null) {
        BookingStore store = new BookingLocalStore(realm);
        currentProperty = store.getPropertyList().toBlocking().first().get(0);
    }
    Log.d("myTag", "getCurrentProperty: "+currentProperty.getName());
    return currentProperty;
}

public void setCurrentProperty(Property currentProperty) {
    this.currentProperty = currentProperty;
    Log.d("myTag", "setCurrentProperty: "+this.currentProperty.getName());
}}

getCurrentProperty()仅调用一次

1 个答案:

答案 0 :(得分:1)

使用getCurrentProperty(Realm)注释@Singleton意味着Dagger会记住该@Provides方法的结果,并将其用于该组件的剩余生命周期。请参阅http://google.github.io/dagger/users-guide.html#singletons-and-scoped-bindings

如果您希望每次请求Property时调用该方法,请删除@Singleton