Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
In this video we'll learn what problems we can solve by using Loaders!
Resources
Related Links
- Loaders Developer Guide
- Threading and Loaders - Android Performance Patterns Video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
[MUSIC]
0:00
Hi, I'm Ben.
0:04
And in this workshop,
we're going to learn about Loaders.
0:06
Loaders are one of the ways we can
do work on a background thread.
0:08
But more importantly,
Loaders are not attached to activities.
0:13
So if you spend a long time downloading
something with a Loader, and
0:17
then rotate the device, even though
the activity would have been killed,
0:20
the loader will be just fine and
ready to give you your data.
0:24
To see why we need Loaders, let's take
a look at some code that loads images into
0:29
a recylcerView using an AsyncTask.
0:34
You can find the code and
0:36
the blog post this code was taken
from in the teacher's notes below.
0:37
So when this app is launched,
we start by setting up a progressBar and
0:41
a recyclerView.
0:44
Then, we kickoff an AsyncTask
to load ten images.
0:47
And while those images are loading, we're
going to figure out how much progress
0:52
we've made, And update the progressBar
after each one finishes.
0:56
Finally, when we're done loading
the images, we hide our progressBar and
1:05
update the recyclerView.
1:10
So what's wrong with this code?
1:15
Let's run it and find out.
1:17
So far so good.
1:27
We saw the progressBar and
we've got our images.
1:28
But if we rotate the app,
1:32
It starts loading a whole
new set of images, not good.
1:35
This is where Loaders come in.
1:40
By using a Loader instead of an AsyncTask,
1:42
we can make sure that we only
download something once.
1:44
The Loader can keep a cache
of what we downloaded.
1:48
And if we try to download it again,
instead of actually doing it again,
1:51
the Loader will just
give us our cache data.
1:54
Even if we rotate the app in
the middle of a download, with Loaders,
1:58
it'll just keep on doing it's
thing in the background.
2:01
And once it's done, we'll get
the update in our new activity and
2:04
everything will be just peachy.
2:08
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up