Skip to content

Commit

Permalink
feat(lib): fix issues when loading same image multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
ihadeed committed Sep 17, 2018
1 parent c13d8cb commit f23056f
Showing 1 changed file with 35 additions and 18 deletions.
53 changes: 35 additions & 18 deletions src/providers/image-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,29 +264,31 @@ export class ImageLoader {

// take the first item from queue
const currentItem: QueueItem = this.queue.splice(0, 1)[0];

// function to call when done processing this item
// this will reduce the processing number
// then will execute this function again to process any remaining items
const done = () => {
this.processing--;
this.processQueue();

// only delete if it's the last/unique occurrence in the queue
if (this.currentlyProcessing[currentItem.imageUrl] !== undefined && !this.currentlyInQueue(currentItem.imageUrl)) {
delete this.currentlyProcessing[currentItem.imageUrl];
}
};

const error = (e) => {
currentItem.reject();
this.throwError(e);
done();
};

if (this.currentlyProcessing[currentItem.imageUrl] === undefined) {
this.currentlyProcessing[currentItem.imageUrl] = new Promise((resolve, reject) => {
// process more items concurrently if we can
if (this.canProcess) this.processQueue();

// function to call when done processing this item
// this will reduce the processing number
// then will execute this function again to process any remaining items
const done = () => {
this.processing--;
this.processQueue();

if (this.currentlyProcessing[currentItem.imageUrl] !== undefined) {
delete this.currentlyProcessing[currentItem.imageUrl];
}
};

const error = (e) => {
currentItem.reject();
this.throwError(e);
done();
};

const localDir = this.getFileCacheDirectory() + this.config.cacheDirectoryName + '/';
const fileName = this.createFileName(currentItem.imageUrl);

Expand All @@ -310,11 +312,13 @@ export class ImageLoader {
}).catch((e) => {
//Could not write image
error(e);
reject(e);
});
},
(e) => {
//Could not get image via httpClient
error(e);
reject(e);
});
},
);
Expand All @@ -324,10 +328,23 @@ export class ImageLoader {
this.getCachedImagePath(currentItem.imageUrl).then(localUrl => {
currentItem.resolve(localUrl);
});
done();
},
(e) => {
error(e);
});
}
}

/**
* Search if the url is currently in the queue
* @param imageUrl {string} Image url to search
* @returns {boolean}
*/
private currentlyInQueue(imageUrl: string) {
return this.queue.some(item => item.imageUrl === imageUrl);
}

/**
* Initialize the cache service
* @param [boolean] replace Whether to replace the cache directory if it already exists
Expand Down

0 comments on commit f23056f

Please sign in to comment.