T
T
tiroman2016-09-14 20:34:04
Android
tiroman, 2016-09-14 20:34:04

Scoped Dagger 2 component?

Hello. There was a question with which I cannot understand. I use Dagger 2 in an android application. There is a component with its own scope

@Module
public class DocumentModule {

    @Provides
    @DocumentScope
    public Document provideDocument(Context context, DocumentLines documentLines) {
        return new Document(context, documentLines);
    }

}

...

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentScope {
}

...

@Component(dependencies = AppComponent.class, modules = {DocumentModule.class})
@DocumentScope
public interface DocumentComponent {

    void inject(DocumentFragment documentFragment);

}

I create this component in a fragment (there are several fragments, ViewPager is used, each fragment needs its own injected document object)
@Inject
    public Document documents;

...

@Override
    public void onCreate(Bundle savedInstanceState) {
     DaggerDocumentComponent.builder().
                appComponent(appComponent).
                build().
                inject(this);
}

The problem occurs when restoring the state of the activity, such as when the screen is rotated, or when the application is restored from the background, in this case the injected documents object is null. Please explain how to manage the scoped component's life cycle so that it is not reset when the activity/fragment is restored?
appComponent and DocumentModule are not listed here, they are dependent on this component and are singletons, there are no questions with them.
I have already read a bunch of materials, looked at the source codes of several projects, it does not fit in my head how to manage such components. Do I need to save the component object to a private variable and save/restore it on onSaveInstanceState/onRestoreInstanceState? It seems to me that this is not so and I misunderstand something.
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tiroman, 2016-09-15
@tiroman

I tried to inject the same object in the activity in which the fragments are located, in onRestoreInstanceState, this object is not null, although I did not take any actions to save the restoration, i.e. it turns out the activity scope component in the activity saves the object in this case
I read the discussion of this topic on reddit and so, I can’t catch the essence of what they write about fragments, but I can’t understand what
upd: I checked again, when the screen is rotated everything is OK, the object not null, when restoring an application from the background null, this is if you open more applications, i.e. simulate a situation when the system nails the activity when there is not enough memory, although the onCreate fragment creates an instance of the component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question