Answer the question
In order to leave comments, you need to log in
Dagger 2. When does a @Singleton object get recreated?
AuthModule.class
@Module
class AuthModule
{
@Provides
@Singleton
AuthManager provideAuthManager(Context context) {
return new AuthManager(context);
}
}
@Singleton
@Component(modules = {
AppModule.class,
DatabaseModule.class,
AuthModule.class,
})
public interface AppComponent
{
void inject(MainActivity activity);
}
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();
}
}
public class BaseActivity extends AppCompatActivity
{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onInjectDependency();
}
public void onInjectDependency() {
//
}
}
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);
}
}
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question