diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/APIRepository.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/APIRepository.kt index 8ec082520fb..ee0e1c493cb 100644 --- a/app/src/main/java/com/lagradost/cloudstream3/ui/APIRepository.kt +++ b/app/src/main/java/com/lagradost/cloudstream3/ui/APIRepository.kt @@ -56,6 +56,13 @@ class APIRepository(val api: MainAPI) { ) private val cache = atomicListOf() + + init { + afterPluginsLoadedEvent += { forceReload -> + if (forceReload) cache.clear() + } + } + private var cacheIndex: Int = 0 const val CACHE_SIZE = 20 @@ -64,16 +71,6 @@ class APIRepository(val api: MainAPI) { } } - private fun afterPluginsLoaded(forceReload: Boolean) { - if (forceReload) { - cache.clear() - } - } - - init { - afterPluginsLoadedEvent += ::afterPluginsLoaded - } - val hasMainPage = api.hasMainPage val providerType = api.providerType val name = api.name diff --git a/app/src/test/java/com/lagradost/cloudstream3/ui/APIRepositoryObserverTest.kt b/app/src/test/java/com/lagradost/cloudstream3/ui/APIRepositoryObserverTest.kt new file mode 100644 index 00000000000..f991ccd89fa --- /dev/null +++ b/app/src/test/java/com/lagradost/cloudstream3/ui/APIRepositoryObserverTest.kt @@ -0,0 +1,45 @@ +package com.lagradost.cloudstream3.ui + +import com.lagradost.cloudstream3.LoadResponse +import com.lagradost.cloudstream3.MainAPI +import com.lagradost.cloudstream3.MainActivity.Companion.afterPluginsLoadedEvent +import com.lagradost.cloudstream3.TvType +import com.lagradost.cloudstream3.mvvm.Resource +import com.lagradost.cloudstream3.newMovieLoadResponse +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class APIRepositoryObserverTest { + @Test fun creatingRepositoriesDoesNotAccumulatePluginObservers() { + val api = object : MainAPI() {} + APIRepository(api) + val before = afterPluginsLoadedEvent.size + repeat(200) { APIRepository(api) } + assertEquals(before, afterPluginsLoadedEvent.size) + } + + @Test fun onlyForcedPluginReloadInvalidatesSharedResponseCache() = runBlocking { + var loads = 0 + val api = object : MainAPI() { + override var name = "ObserverReloadRegression" + override var mainUrl = "https://example.com" + override suspend fun load(url: String): LoadResponse { + loads++ + return newMovieLoadResponse("Example", url, TvType.Movie, "video") + } + } + val repo = APIRepository(api) + afterPluginsLoadedEvent.invoke(true) + assertTrue(repo.load("https://example.com/movie") is Resource.Success) + assertTrue(APIRepository(api).load("https://example.com/movie") is Resource.Success) + assertEquals(1, loads) + afterPluginsLoadedEvent.invoke(false) + assertTrue(repo.load("https://example.com/movie") is Resource.Success) + assertEquals(1, loads) + afterPluginsLoadedEvent.invoke(true) + assertTrue(repo.load("https://example.com/movie") is Resource.Success) + assertEquals(2, loads) + } +}