2016-09-05 48 views
0

我可以更改存儲在Application module中的值並將其返回到新的活動或其他位置嗎?我試過這個代碼,我預計@Provides批註的方法將要求每因爲我叫DaggerExampleBuilder.builde().appComponent(...).build().inject()我是否可以更新ApplicationModule並獲得每次注入的更新值

這是從我的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

註解getCurrentProperty(Realm)使用@Singleton表示Dagger將記憶該方法的結果並將其用於該組件的其餘生命週期。見http://google.github.io/dagger/users-guide.html#singletons-and-scoped-bindings

如果您希望每次請求Property時調用該方法,請刪除@Singleton

+0

+1。在這種情況下,如果你想單身人士的行爲,你需要重定向@Singleton綁定(可能與@Qualifier)或使用[一些其他技術來確保單身人士行爲](https://google.github.io /guava/releases/19.0/api/docs/com/google/common/base/Suppliers.html#memoize(com.google.common.base.Supplier))。 –

相關問題