Note: This question is different from this question as no answers given for the question explain how to cancel the image request which we make for preloaded image.
I have an infinite list(RecyclerView
). I need to preload images of next 'x'(read 3) items from the last bound item of the RecyclerView
. Also, when a particular Viewholder
is detached from the window, I need to cancel the preload image request if it is already not successful.
I have achieved it in the following way.
Map<Integer, SimpleTarget> simpleTargetMap = new HashMap<>();
public void preloadImage(int position, Context context, String imageUrl) {
SimpleTarget simpleTarget = new SimpleTarget() {
@Override
public void onResourceReady(@NonNull Object resource, @Nullable Transition transition) {
simpleTargetMap.remove(position);
}
};
Glide.with(context)asBitmap().load(imageUrl).into(simpleTarget);
simpleTargetMap.put(position, simpleTarget);
}
@Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
SimpleTarget simpleTarget = simpleTargetMap.get(holder.getAdapterPosition());
Glide.with(context).clear(simpleTarget);
simpleTargetMap.remove(holder.getAdapterPosition());
}
I am able to achieve the desired result. But I am facing memory issues with this approach. If I don't use the preloading, my memory usage is between 150-200 mb. But if I start using the preload, the memory usage jumps to 250-300 mb. After taking a heap dump, I see a lot of Bitmap objects which are not there(not as many) if I don't use preload.
So what is the best way to preload an image in Glide where I can also cancel the image request in the future? And if I don't use SimpleTarget, is there any way of cancelling an image request based only of the imageUrl?
Load images into memory cache using preload method:
Glide.with(context)
.load(url)
.preload(500, 500);
You can later use the cached images using:
Glide.with(yourFragment)
.load(yourUrl)
.into(yourView);