Downloading Lots of Small Things

Currently, PhotoGallery’s networking works like this: PhotoGalleryViewModel calls FlickrFetchr().fetchPhotos() to download JSON data from Flickr. FlickrFetchr immediately returns an empty LiveData<List<GalleryItem>> object and enqueues an asynchronous Retrofit request to retrieve the data from Flickr. That network request executes on a background thread.

When the data download is complete, FlickrFetchr parses the JSON data into a list of GalleryItems and publishes the list to the live data object it returned. Each GalleryItem now has a URL where a thumbnail-size photo lives.

The next step is to go and get those thumbnails. How will you go about this? FlickrFetchr requests only 100 URLs by default, so your GalleryItem list holds at most 100 URLs. So one option would be to download the images one after another until you have all 100, notify the ViewModel, and ultimately display the images en masse in the RecyclerView.

However, downloading the thumbnails all at once would cause two problems. The first is that it could take a while, and the UI would not be updated until the downloading was complete. On a slow connection, users would be staring at a wall of Bills for a long time.

The second problem is the cost of having to store the entire set of images. One hundred thumbnails will fit into memory easily. But what if it were 1,000? What if you wanted to implement infinite scrolling? Eventually, you would run out of space.

Given these problems, real-world apps often download images only when they need to be displayed onscreen. Downloading on demand puts the responsibility on the RecyclerView and its adapter. The adapter triggers the image downloading as part of its onBindViewHolder(…) implementation.

OK, so how will you go about that? You could enqueue a separate asynchronous Retrofit request for each image download. However, you would need to keep track of all the Call objects and manage their lives in relation to each view holder and to the fragment itself.

Instead you are going to create a dedicated background thread. This thread will receive and process download requests one at a time, and it will provide the resulting image for each individual request as the corresponding download completes. Since all the requests are managed by the background thread, you can easily clean up all the requests or stop the thread altogether, rather than having to manage a whole bunch of separate requests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.238.118.192