Dagger2 scopes and activity lifecycle

前端 未结 2 1833
名媛妹妹
名媛妹妹 2020-12-10 18:52

I have an Android Activity that I\'m using Dagger2 to inject a Presenter into. I\'d like my Presenter to be capable of holding state even if a configuration change occurs.

2条回答
  •  情话喂你
    2020-12-10 19:11

    According to this article about Custom Scopes:

    http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/

    In short - scopes give us “local singletons” which live as long as scope itself.

    Just to be clear - there are no @ActivityScope or @ApplicationScope annotations provided by default in Dagger 2. It’s just most common usage of custom scopes. Only @Singleton scope is available by default (provided by Java itself), and the point is using a scope is not enough(!) and you have to take care of component that contains that scope. This mean keeping a reference to it inside Application class and reuse it when Activity changes.

    public class GithubClientApplication extends Application {
    
        private AppComponent appComponent;
        private UserComponent userComponent;
    
        //...
    
        public UserComponent createUserComponent(User user) {
            userComponent = appComponent.plus(new UserModule(user));
            return userComponent;
        }
    
        public void releaseUserComponent() {
            userComponent = null;
        }
    
        //...
    }
    

    You can take a look at this sample project:

    http://github.com/mmirhoseini/marvel

    and this article:

    https://hackernoon.com/yet-another-mvp-article-part-1-lets-get-to-know-the-project-d3fd553b3e21

    to get more familiar with MVP and learn how dagger scope works.

提交回复
热议问题