-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[resources] Check cached deferreds and drop them if they are cancelle…
…d. (#4819) Before the fix we could cancel a coroutine and the cancelled deferred was saved in cache. ## Release Notes ### Fixes - Resources - _(prerelease fix)_ Fix a cached empty resource on a Compose for Web if the resource loading was canceled during progress (cherry picked from commit dbab893)
- Loading branch information
Showing
4 changed files
with
57 additions
and
64 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
...nts/resources/library/src/commonMain/kotlin/org/jetbrains/compose/resources/AsyncCache.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package org.jetbrains.compose.resources | ||
|
||
import kotlinx.coroutines.CoroutineStart | ||
import kotlinx.coroutines.Deferred | ||
import kotlinx.coroutines.async | ||
import kotlinx.coroutines.coroutineScope | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
|
||
internal class AsyncCache<K, V> { | ||
private val mutex = Mutex() | ||
private val cache = mutableMapOf<K, Deferred<V>>() | ||
|
||
suspend fun getOrLoad(key: K, load: suspend () -> V): V = coroutineScope { | ||
val deferred = mutex.withLock { | ||
var cached = cache[key] | ||
if (cached == null || cached.isCancelled) { | ||
//LAZY - to free the mutex lock as fast as possible | ||
cached = async(start = CoroutineStart.LAZY) { load() } | ||
cache[key] = cached | ||
} | ||
cached | ||
} | ||
deferred.await() | ||
} | ||
|
||
//@TestOnly | ||
fun clear() { | ||
cache.clear() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters