Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/main/java/org/openedx/app/di/ScreenModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ val screenModule = module {
factory { CalendarInteractor(get()) }

single { CourseRepository(get(), get(), get(), get(), get()) }
factory { CourseInteractor(get()) }
factory { CourseInteractor(get(), get()) }
single<org.openedx.core.domain.interactor.CourseInteractor> { get<CourseInteractor>() }

viewModel { (pathId: String, infoType: String) ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,79 @@ import java.util.concurrent.ConcurrentHashMap
* @param V the type of cached values
* @param fetch the suspend function to fetch data for a given key
* @param persist optional callback invoked after successful fetch (e.g., to save to database)
* @param autoCache whether to store a successful fetch result in the cache before [persist] runs
* @param activeGeneration optional function that returns the current cache version; values saved
* under a different version are not returned
*/
class CoalescingCache<K, V>(
private val fetch: suspend (K) -> V,
private val persist: (suspend (K, V) -> Unit)? = null
private val persist: (suspend (K, V) -> Unit)? = null,
private val autoCache: Boolean = true,
private val activeGeneration: (() -> Long)? = null,
) {
private val cache = ConcurrentHashMap<K, V>()
private data class CacheEntry<V>(
val value: V,
val generation: Long,
)

private val cache = ConcurrentHashMap<K, CacheEntry<V>>()
private val pending = ConcurrentHashMap<K, CompletableDeferred<V>>()

/**
* Returns cached value for the key, or null if not cached.
* Returns the cached value for [key], or null when no usable value is cached.
*
* When [activeGeneration] is set, a value saved under a different version is not usable.
*/
fun getCached(key: K): V? = cache[key]
fun getCached(key: K): V? {
val entry = cache[key] ?: return null
val generationProvider = activeGeneration

return when {
generationProvider == null -> {
entry.value
}

entry.generation == generationProvider() -> {
entry.value
}

else -> {
cache.remove(key, entry)
null
}
}
}

/**
* Manually sets a cached value.
* Stores a cached value.
*
* When [activeGeneration] is set and [writeGeneration] is supplied, stores the value only if
* that version is still current.
*/
fun setCached(key: K, value: V) {
cache[key] = value
fun setCached(
key: K,
value: V,
writeGeneration: Long = UNSPECIFIED_GENERATION,
) {
val generationProvider = activeGeneration
if (generationProvider == null) {
cache[key] = CacheEntry(value, DEFAULT_GENERATION)
return
}

if (writeGeneration == UNSPECIFIED_GENERATION) {
val currentGeneration = generationProvider()
cache[key] = CacheEntry(value, currentGeneration)
return
}

cache.compute(key) { _, currentEntry ->
if (generationProvider() == writeGeneration) {
CacheEntry(value, writeGeneration)
} else {
currentEntry
}
}
}

/**
Expand All @@ -40,6 +95,23 @@ class CoalescingCache<K, V>(
cache.clear()
}

/**
* Stops waiting callers from sharing requests that were pending when this method began.
*
* It removes each recorded request before cancelling callers waiting for it, so a caller that
* resumes can start a new request. A fetch that already started can still finish. When it does,
* it removes a pending request only if that request still belongs to it, not a newer request
* for the same key.
*/
fun cancelPending() {
val pendingSnapshot = HashMap(pending)
for ((key, deferred) in pendingSnapshot) {
if (pending.remove(key, deferred)) {
deferred.cancel()
}
}
}

/**
* Gets the value from cache or fetches it.
*
Expand All @@ -49,22 +121,24 @@ class CoalescingCache<K, V>(
*/
suspend fun getOrFetch(key: K, forceRefresh: Boolean = false): V {
if (!forceRefresh) {
cache[key]?.let { return it }
getCached(key)?.let { return it }
}

val (deferred, isOwner) = getOrCreateDeferred(key)
return if (isOwner) {
val (deferred, startsFetch) = getOrCreateDeferred(key)
return if (startsFetch) {
try {
val result = fetch(key)
cache[key] = result
persist?.invoke(key, result)
deferred.complete(result)
result
val value = fetch(key)
if (autoCache) {
setCached(key, value)
}
persist?.invoke(key, value)
deferred.complete(value)
value
} catch (e: Exception) {
deferred.completeExceptionally(e)
throw e
} finally {
pending.remove(key)
pending.remove(key, deferred)
}
} else {
deferred.await()
Expand All @@ -77,4 +151,9 @@ class CoalescingCache<K, V>(
val existing = pending.putIfAbsent(key, deferred)
return if (existing != null) existing to false else deferred to true
}

private companion object {
const val DEFAULT_GENERATION = 0L
const val UNSPECIFIED_GENERATION = Long.MIN_VALUE
}
}
Loading
Loading