2

Sample scheme:

enter image description here

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?

Alexandr
  • 3,859
  • 5
  • 32
  • 56
  • @Alexandra, Am trying to update my dagger injected object throughout my application reference. Initially it was setted with no value. Am trying to modify the object from shared preferences. I couln't able to reassign the value in all part of application code. Give me valuable solution to achieve this.Struck on this for two days. – Senthil Mg Jan 16 '18 at 19:08
  • @SenthilMg create separate well-explained question for this purpose :) – Alexandr Jan 16 '18 at 22:10

1 Answers1

6

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.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134