Does RoboGuice re-instantiate previously existing objects when onCreate() is called

505 Views Asked by At

My Activity is injected with a number of objects that are initialized before onCreate is called for the first time. When my Activity finishes by invoking the finish method, it passes through onDestroy before returning to the main "OS desktop" window. I then invoke my application again, and onCreate is again called. This time though my view remains the same as when finish was initially called above. Therefore, I am wondering if RoboGuice re-instantiates the injected objects again? If not, is there a way for me to do this? Thanks.

2

There are 2 best solutions below

1
abombss On

Take a look at the Android activity lifecycle docs.

If onCreate is called by Android then a new instance of your activity was created and any non-singleton components will be instantiated, and all components will be injected by roboguice.

If you only need a single instance of a component you can make it a singleton. Just be cautious of memory use with singletons because they will live for the duration of the application process. So even if an activity has been destroyed but your app process is still running those singletons will be consuming memory.

Roboguice is just a wrapper around guice. If you are interested in pursuing other options for getting instances of classes take a look at Bindings, Scopes and Providers in guice.

0
Paweł Byszewski On

are you saying that these are not re-instantiated then?

when onCreate() is called ex. when you change phone orientation every object are injected once again. But if one of injected object is Singleton, the same instance of object will be injected. "Singleton" works in scope of whole application so the activity lifecycle does not ifluence on signleton objects.