這篇文章主要為大家展示了“如何解決Glide緩存key的問題”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“如何解決Glide緩存key的問題”這篇文章吧。
最近項目里面有個地方是在前面用glide加載圖片后,后面再另外一個地方加載相同圖片時沒有復用glide的緩存,而是自己另外又重新緩存了一套。
查找后發現問題是glide緩存的key不一致的問題。
從key的生成可以看到和很多參數有關,逐一排查后,發現了width和height還有id不一樣。這3個是項目外面傳進來的。
EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(), loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(), transcoder, loadProvider.getSourceEncoder());
key的作用大概是通過下面三步里面去找數據
如果都為null,就會進入函數最后邊的開線程去decode(相當于緩存沒找到,準備重新加載數據吧)
EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable); DecodeJob<T, Z, R> decodeJob = new DecodeJob<T, Z, R>(key, width, height, fetcher, loadProvider, transformation, transcoder, diskCacheProvider, diskCacheStrategy, priority); EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority); jobs.put(key, engineJob); engineJob.addCallback(cb); engineJob.start(runnable);
進入EngineRunnable的run方法看
resource = decode();
private Resource<?> decode() throws Exception {
if (isDecodingFromCache()) {
return decodeFromCache();
} else {
return decodeFromSource();
}
}其中loadCache還是loadFromSource的條件
private boolean isDecodingFromCache() {
return stage == Stage.CACHE;
}默認stage會進去,走到decodeFromCache(),由于cache里沒有,返回null到run方法里面觸發加載失敗的回調
if (resource == null) {
onLoadFailed(exception);
} else {
onLoadComplete(resource);
}在回調中重新提交一個runnable,改變stage,下一次run執行時,stage==source,就不會去loadCache,而是loadSource。(開線程加載大概流程感覺就像是默認先去緩存中找,沒找到就重新加載)
private void onLoadFailed(Exception e) {
if (isDecodingFromCache()) {
stage = Stage.SOURCE;
manager.submitForSource(this);
} else {
manager.onException(e);
}
}loadSource會一路走到
private Resource<T> decodeFromSourceData(A data) throws IOException {
final Resource<T> decoded;
if (diskCacheStrategy.cacheSource()) {
decoded = cacheAndDecodeSourceData(data);
} else {
long startTime = LogTime.getLogTime();
decoded = loadProvider.getSourceDecoder().decode(data, width, height);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Decoded from source", startTime);
}
}這里回調的decode就是項目中自己設置的sourceDecoder
項目內的代碼象征性的打碼:

之前id和寬高傳的不一樣,導致key不一樣,然后Glide加載的時候通過key找不到緩存,最后就又回調到項目里面的decode那里來了。
改完后,第一次decode完后,后面用緩存就不會再進入decode了。
以上是“如何解決Glide緩存key的問題”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。