Loaders and Fragments, a history
From the beginning, Loaders and Fragments were pretty tightly tied together at the hip. This meant that a lot of the code in
Fragment were there to support Loaders, despite the fact that there are indeed fairly independent. It also meant that the lifecycle and guarantees of Loaders were totally unique and subject to their own set of fun and exciting behavior differences and bugs when compared to the Activity, Fragment, and Architecture Component lifecycle.
What’s changed in 27.1.0
With 27.1.0, the technical debt of Loaders has been greatly reduced: the lines of code needed to implement
LoaderManager went down to about a third of its former size and there’s many, many more tests to backfill to ensure that Loaders remain in a good state going forward.
A lot of this is thanks to Architecture Components. More specifically, ViewModels (for retaining state across configuration changes) and LiveData (for providing lifecycle aware callbacks). Loaders now benefit from these same higher level, super well tested components as their basis, reducing ongoing bit rot and allowing improvements on the reliability/guarantees added there to propagate to Loaders automatically.
This does mean a few behavior changes though.
For one, calling
destroyLoader now must be done on the main thread. This offers some very specific guarantees on when callbacks stop or start — you’ll never get a callback to
onLoadFinished after destroying a Loader for instance.
Note: while technically you could do Loader operations on other threads prior to this release,
LoaderManagerwas never thread safe, leading to often undefined behavior.
onLoadFinished now follow the same rules as LiveData Observers for when they will be called — always between
onStop and never after
onSaveInstanceState. This allows you to safely do Fragment Transactions in
What should I use and where are Loaders going?
As I mentioned in my previous blog post, Lifecycle Aware Data Loading with Architecture Components, I feel like ViewModels+LiveData are definitely a more flexible, easier to understand system that I’d strongly recommend to developers. However, if you have existing APIs built around Loaders, these changes should greatly improve the reliability and stability of the component going forward.
Try it out!
If you’re using Loaders, please take an extra close look sooner rather than later and note the behavior changes listed in the release notes.
Note: Obviously, these changes only apply to Support Library Loaders. If you are using Android framework Loaders, please switch to the Support Library Loaders as soon as possible. There are no bug fixes or improvements planned for the framework Loader APIs.