Skip to content

Commit

Permalink
Ensure RealImageLoader is fully initialized before registering system…
Browse files Browse the repository at this point in the history
… callbacks. (#1465)

* Ensure RealImageLoader is fully initialized before registering system callbacks.

* Docs.
  • Loading branch information
colinrtwhite committed Sep 18, 2022
1 parent 0b07425 commit 01d9643
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
Expand Up @@ -13,6 +13,7 @@ import coil.memory.MemoryCache.Key
import coil.memory.MemoryCache.Value
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class SystemCallbacksTest {
Expand Down Expand Up @@ -56,10 +57,10 @@ class SystemCallbacksTest {
memoryCache[Key("1")] = Value(createBitmap(1000, 1000, Bitmap.Config.ARGB_8888))
memoryCache[Key("2")] = Value(createBitmap(1000, 1000, Bitmap.Config.ARGB_8888))

assertTrue(memoryCache.size == 8000000)
assertEquals(8_000_000, memoryCache.size)

systemCallbacks.onTrimMemory(TRIM_MEMORY_COMPLETE)

assertTrue(memoryCache.size == 0)
assertEquals(0, memoryCache.size)
}
}
9 changes: 6 additions & 3 deletions coil-base/src/main/java/coil/RealImageLoader.kt
Expand Up @@ -112,6 +112,11 @@ internal class RealImageLoader(
EngineInterceptor(this, requestService, logger)
private val isShutdown = AtomicBoolean(false)

init {
// Must be called only after the image loader is fully initialized.
systemCallbacks.register()
}

override fun enqueue(request: ImageRequest): Disposable {
// Start executing the request on the main thread.
val job = scope.async {
Expand Down Expand Up @@ -213,9 +218,7 @@ internal class RealImageLoader(
@Suppress("SAFE_CALL_WILL_CHANGE_NULLABILITY", "UNNECESSARY_SAFE_CALL")
internal fun onTrimMemory(level: Int) {
// https://github.com/coil-kt/coil/issues/1443
try {
memoryCacheLazy?.value?.trimMemory(level)
} catch (_: NullPointerException) {}
memoryCacheLazy?.value?.trimMemory(level)
}

override fun shutdown() {
Expand Down
2 changes: 1 addition & 1 deletion coil-base/src/main/java/coil/util/SystemCallbacks.kt
Expand Up @@ -39,7 +39,7 @@ internal class SystemCallbacks(
val isOnline get() = _isOnline
val isShutdown get() = _isShutdown.get()

init {
fun register() {
context.registerComponentCallbacks(this)
}

Expand Down

0 comments on commit 01d9643

Please sign in to comment.