Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Last active April 27, 2019 12:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbeyls/ca39c38f1ad451c35fc66142989e9e76 to your computer and use it in GitHub Desktop.
Save cbeyls/ca39c38f1ad451c35fc66142989e9e76 to your computer and use it in GitHub Desktop.
Activity to restore the safe Loaders behavior of support libraries < 24.0.0 in recent versions
package android.support.v4.app;
/**
* Inherit from this class to prevent Loaders from being forcefully retained during a configuration change.
* Forceful retain currently causes all stopped Loaders to briefly start, causing unexpected issues for detached fragments.
* This restores the Loaders behavior of support libraries < 24.0.0
*
* @author Christophe Beyls
* @see <a href="https://issuetracker.google.com/issues/37916599">Bug report</a>
*/
public class SafeLoadersFragmentActivity extends FragmentActivity {
@Override
void doReallyStop(boolean retaining) {
// Ensure the Activity Loaders are only stopped once and never restarted during stop
if (!mReallyStopped) {
super.doReallyStop(retaining);
}
}
@Override
public Object onRetainCustomNonConfigurationInstance() {
// All loaders are already stopped or retained at that point, but calling this method again
// sets a flag to prevent them from being forcefully retained during the next phase
mFragments.doLoaderStop(false);
return super.onRetainCustomNonConfigurationInstance();
}
/**
* Hack to force update the LoaderManager in RETAINED fragments
* in order to avoid memory leaks and Loaders malfunction. Call this in Fragment.onAttach().
*/
public static void updateLoaderManager(Fragment fragment) {
fragment.mLoaderManager = null;
fragment.mCheckedForLoaderManager = false;
}
}
@cbeyls
Copy link
Author

cbeyls commented Apr 27, 2019

Deprecated. Please migrate to LiveData and ViewModel from architecture components.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment