How to have an expired CACHE for Glide image library

Mladen Rakonjac
Fleka Developers
Published in
2 min readAug 8, 2017

--

In our new Android application in fleka, we have n categories from 3rd party API provider, where each of them have its own image. Due to some 3rd party API provider limitation, we always have the same url for each category, even though the image changes in time. For fetching images, we are using Glide image library that has great Cache options. The problem is how to know when Glide has to download it again cause URL is always same. So, we decided to force Glide to download image again every new week. But how to do that?

Glide has an option to invalidate Cache using diskCacheStrategy()and DiskCacheStrategy.NONE. The problem with this was how to ensure it will be called only first time in week. So, we found a better solution:

Glide signature() API.

Glide signature API helps us to have more control over the cache. For example, we can provide versionNumberOfCategoryImages, so it will download the image again, once when we have provided new versionNumberOfCategoryImages. Our versionNumberOfCategoryImages will be unique id int of current week. We can get it taking Year and Week of Year from current Date:

Calendar calendar = Calendar.getInstance();
int versionNumber = calendar.get(Calendar.WEEK_OF_YEAR) * 100 +
calendar.get(Calendar.YEAR);

To have the signature as int, we have to define our own Signature by implementing the Key interface:

public class IntegerVersionSignature implements Key {
private int currentVersion;

public IntegerVersionSignature(int currentVersion) {
this.currentVersion = currentVersion;
}

@Override
public boolean equals(Object o) {
if (o instanceof IntegerVersionSignature) {
IntegerVersionSignature other = (IntegerVersionSignature) o;
return currentVersion = other.currentVersion;
}
return false;
}

@Override
public int hashCode() {
return currentVersion;
}

@Override
public void updateDiskCacheKey(MessageDigest md) {
messageDigest.update(ByteBuffer.allocate(Integer.SIZE).putInt(signature).array());
}
}

So, to download images you have to use:

Glide.with(getContext())
.load(categoryModel.getImageUrl())
.signature(new IntegerVersionSignature(versionNumber))
.placeholder(placeHolder)
.into(categoryImageView);

If you somehow know when images are changed, you may not use id of the current week. You can use, for example, Firebase Remote Config to provide new versionNumber of images once they have been changed.

--

--