Sample scheme:
It based on Mosby examples. I want to share Project
object between ProjectFragment
and ProjectHistoryFragment
with @PerProject
scope.
ProjectModule:
@Module
public class ProjectModule {
private Project project;
public ProjectModule(Project project) {
this.project = project;
}
@Provides
@PerProject
public Project provideProject() {
return project;
}
}
ProjectModule
and ProjectComponent
will be created by ProjectFragment
and shared to every Project-dependent fragment
. Nice.
But there is a problem. What if I need to update the title of Project
? In my case, Project
is a final object without any setters. Project
can be modified only in ProjectFragment, so I can update and reset module's
value for future injections. But I think that it is bad practice. Can someone give better advice?
Don't change values within your modules.
A component (and its included modules) have a set of objects they inject where you need them. They get cached, reused, and so on. Switching an object will leave you with an inconsistent state.
If you need to change an object then create a new component, with new modules.
If you still need to change the project object without recreating everything, then don't inject the Project
itself but rather some ProjectManager
, which could also implement some Observable
pattern to notify you if the Project
changed. This way you can modify your project and react to changes.