Sobes.tech
Junior — Middle

How to save and restore MVP and Dagger 2 components when changing screen orientation without their complete recreation upon Activity restart?

sobes.tech AI

Answer from AI

To preserve and restore MVP components and Dagger 2 when changing screen orientation without their complete recreation, it is common to save components in an object that survives the Activity's recreation, such as in a ViewModel or in a Fragment with setRetainInstance(true) (although the latter method is deprecated).

Main approaches:

  1. Using ViewModel:

    • Create the Dagger component in the ViewModel, which lives longer than the Activity and survives rotation.
    • In the Activity, obtain the component from the ViewModel to avoid recreating it.
  2. Using Singleton approach with keys:

    • Create a map of components in a static field or in the Application.
    • When creating the Activity, generate a unique key (e.g., UUID) and save it in onSaveInstanceState.
    • When recreating the Activity, retrieve the key and get the component from the map.
  3. Using Fragment with setRetainInstance(true):

    • Create an invisible Fragment that holds the component.
    • The Fragment is not recreated on rotation, so the component is preserved.

Example with ViewModel:

class MyViewModel : ViewModel() {
    val component: MyComponent = DaggerMyComponent.create()
}

class MyActivity : AppCompatActivity() {
    private lateinit var component: MyComponent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
        component = viewModel.component
        // Use the component for injections
    }
}

This approach helps avoid recreating components when the configuration changes and preserves the dependency state.

How to save and restore MVP and Dagger 2 components… - sobes.tech