S
S
Sergey Semenko2017-02-16 14:44:45
Android
Sergey Semenko, 2017-02-16 14:44:45

Dagger 2. When does a @Singleton object get recreated?

AuthModule.class

@Module
class AuthModule
{
    @Provides
    @Singleton
    AuthManager provideAuthManager(Context context) {
        return new AuthManager(context);
    }
}

AppComponent.class:
@Singleton
@Component(modules = {
        AppModule.class,
        DatabaseModule.class,
        AuthModule.class,
})
public interface AppComponent
{
    void inject(MainActivity activity);
}

application.class:
public class Application extends android.app.Application
{
    private static AppComponent mAppComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        setup();
    }

    public static AppComponent getAppComponent() {
        return mAppComponent;
    }

    private void setup() {
        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }
}

BaseActivity.class:
public class BaseActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onInjectDependency();
    }

    public void onInjectDependency() {
        //
    }
}

MainActivity class:
public class MainActivity extends BaseActivity
{
    @Inject AuthManager authManager;
    private User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = authManager.getCurrentUser();
    }

    @Override
    public void onInjectDependency() {
        Application.getAppComponent().inject(this);
    }
}

A couple of times there was a situation in which the AuthManager was recreated, while the application was active (visible to the user). For my application, this is very bad, since the user enters a pin code to access the authorization data (when the application starts).
Can this be dealt with somehow, or do we need to rely on re-creation?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2017-02-16
@abler98

You need code when you create the component and when you inject the activity. If it is recreated in such a situation, then you are injecting several times, while using different instances of the component.

D
Dmitry Serkov, 2017-02-16
@Hutaab

Maybe so:

private void setup() {
        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .authModule(new AuthModule(this)) //добавить
                .build();
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question