Describe a scenario where using a retained fragment is beneficial and explain how to implement it. What are the potential drawbacks of using retained fragments?
Android interview question for Advanced practice.
Answer
A retained fragment is beneficial when you need to maintain a running background task or a complex object that is expensive to recreate across configuration changes. For example, a fragment that manages a complex network connection, parses a large amount of data, or holds a reference to a running thread would be a good candidate. By retaining the fragment, the background task can continue running uninterrupted by the Activity's recreation. To implement a retained fragment, you call setRetainInstance(true) in the fragment's onCreate() method. java @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } Potential drawbacks of using retained fragments include: Memory Leaks: This is the biggest risk. A retained fragment can easily leak memory if it holds a reference to any view or any object tied to the old Activity's context. All references to views must be nulled out in onDestroyView(). Discouraged Pattern: The use of retained fragments is now generally discouraged in favor of using ViewModels, which are specifically designed to handle data persistence across configuration changes in a more robust and lifecycle-aware manner. Complexity: Managing the state of a headless, retained fragment can add complexity to the app's architecture and make debugging more difficult.
Explanation
Retained fragments can be a powerful tool, but they come with trade-offs. Understanding these trade-offs is essential for making informed decisions about when and how to use them.