diff --git a/library/src/main/java/com/danikula/videocache/ProxyCache.java b/library/src/main/java/com/danikula/videocache/ProxyCache.java index 8335b46..5fa4176 100644 --- a/library/src/main/java/com/danikula/videocache/ProxyCache.java +++ b/library/src/main/java/com/danikula/videocache/ProxyCache.java @@ -134,6 +134,7 @@ private void readSource() { notifyNewCacheDataAvailable(offset, sourceAvailable); } tryComplete(); + onSourceRead(); } catch (Throwable e) { readSourceErrorsCount.incrementAndGet(); onError(e); @@ -143,6 +144,12 @@ private void readSource() { } } + private void onSourceRead() { + // guaranteed notify listeners after source read and cache completed + percentsAvailable = 100; + onCachePercentsAvailableChanged(percentsAvailable); + } + private void tryComplete() throws ProxyCacheException { synchronized (stopLock) { if (!isStopped() && cache.available() == source.length()) { diff --git a/test/src/test/java/com/danikula/videocache/HttpProxyCacheTest.java b/test/src/test/java/com/danikula/videocache/HttpProxyCacheTest.java index e28e259..df80839 100644 --- a/test/src/test/java/com/danikula/videocache/HttpProxyCacheTest.java +++ b/test/src/test/java/com/danikula/videocache/HttpProxyCacheTest.java @@ -166,6 +166,19 @@ public void testLoadEmptyFile() throws Exception { assertThat(response.data).isEmpty(); } + @Test + public void testCacheListenerCalledAtTheEnd() throws Exception { + File file = ProxyCacheTestUtils.newCacheFile(); + File tempFile = ProxyCacheTestUtils.getTempFile(file); + HttpProxyCache proxyCache = new HttpProxyCache(new HttpUrlSource(HTTP_DATA_URL), new FileCache(file)); + CacheListener listener = Mockito.mock(CacheListener.class); + proxyCache.registerCacheListener(listener); + processRequest(proxyCache, "GET /" + HTTP_DATA_URL + " HTTP/1.1"); + + Mockito.verify(listener).onCacheAvailable(tempFile, HTTP_DATA_URL, 100); // must be called for temp file ... + Mockito.verify(listener).onCacheAvailable(file, HTTP_DATA_URL, 100); // .. and for original file too + } + @Test(expected = ProxyCacheException.class) public void testTouchSourceForAbsentSourceInfoAndCache() throws Exception { SourceInfoStorage sourceInfoStorage = SourceInfoStorageFactory.newEmptySourceInfoStorage();