In Dagger are Singletons within the sub-graph cached or will they always be recreated when a new activity sub-graph is constructed?

孤街醉人 提交于 2019-12-08 11:31:30

How MyPresentationModule is injected depends on how your modules are specified. For example, assume that you are injecting the class Foo:

public class Foo {
    private final MyPresentationModel model;
    @Inject
    public Foo(MyPresentationModel model) {
        this.model = model;
    }
}

If your modules are structured like (A), then the MyPresentationModel singleton will be injected into Foo by the main object graph:

EXAMPLE A

@Module(injects = { Foo.class })
public class MainModule { ... }

@Module(addsTo = MainModule.class, injects = { MyPresentationModel.class })
public class SubModule { ...}

Alternatively, if your modules are structured like (B), then the MyPresentationModel singleton will be injected into Foo by the subgraph:

EXAMPLE B

@Module
public class MainModule { ... }

@Module(addsTo = MainModule.class, injects = { Foo.class, MyPresentationModel.class })
public class SubModule { ... }

In your particular case, since you have specified that MyAppModule injects MyApplication, I would guess that you are trying to inject MyPresentationModel into your Application class. This is probably not what you want to do. You probably want inject this into your Activity class using the submodule, as in (C).

EXAMPLE C

@Module(injects = { MainActivity.class, MyPresentationModel.class },
    addsTo = MyAppModule.class,
    library = true)
public class SubModule { ... }

public class MainActivity {
    @Inject MyPresentationModel presentationModel;
    ...
}

If you do this the MyPresentationModel singleton will be bound to the Activity subgraph instead of the main graph, and should be disposed when the Activity is destroyed.

Once you have a handle on Dagger, you might want to check out Mortar, which gives you finer-grained control over creation and destruction of ObjectGraph subscopes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!