Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,27 @@

package com.adobe.marketing.mobile.concierge.ui.components.image

import android.graphics.Bitmap
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toPixelMap
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.unit.dp
import com.adobe.marketing.mobile.concierge.ui.theme.ConciergeTheme
import com.adobe.marketing.mobile.concierge.utils.image.DefaultImageProvider
import com.adobe.marketing.mobile.concierge.utils.image.ImageProvider
import com.adobe.marketing.mobile.concierge.utils.image.LocalImageProvider
import java.io.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test

Expand All @@ -28,6 +44,138 @@ class AsyncImageTest {
@get:Rule
val composeTestRule = createComposeRule()

@Test
fun asyncImage_urlChangesDuringDownload_rendersNewImageWithoutReportingCancellation() {
assertImageReloadsAfterUrlChange(PreviousImageState.LOADING)
}

@Test
fun asyncImage_urlChangesAfterSuccess_rendersNewImage() {
assertImageReloadsAfterUrlChange(PreviousImageState.SUCCESS)
}

@Test
fun asyncImage_urlChangesAfterError_rendersNewImage() {
assertImageReloadsAfterUrlChange(PreviousImageState.ERROR)
}

@Test
fun asyncImage_urlChangesAfterCacheHit_rendersNewImage() {
assertImageReloadsAfterUrlChange(PreviousImageState.CACHED)
}

private fun assertImageReloadsAfterUrlChange(previousState: PreviousImageState) {
val oldUrl = "https://example.com/old.png"
val newUrl = "https://example.com/new.png"
val provider = ControlledImageProvider()
val oldImage = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888).apply {
eraseColor(android.graphics.Color.RED)
}
val newImage = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888).apply {
eraseColor(android.graphics.Color.BLUE)
}
val failure = IOException("Old image failed")
val errors = mutableListOf<Throwable>()
val url = mutableStateOf(oldUrl)
if (previousState == PreviousImageState.CACHED) {
provider.cached[oldUrl] = oldImage
}

composeTestRule.setContent {
ConciergeTheme {
CompositionLocalProvider(LocalImageProvider provides provider) {
AsyncImage(
url = url.value,
contentDescription = "Loaded image",
modifier = Modifier.size(64.dp),
onError = { errors.add(it) }
)
}
}
}
composeTestRule.runOnIdle {
when (previousState) {
PreviousImageState.SUCCESS -> provider.complete(oldUrl, oldImage)
PreviousImageState.ERROR -> provider.fail(oldUrl, failure)
else -> Unit
}
}
composeTestRule.waitForIdle()
if (previousState == PreviousImageState.SUCCESS || previousState == PreviousImageState.CACHED) {
assertRenderedImageColor(Color.Red)
}
composeTestRule.runOnIdle {
assertEquals(
if (previousState == PreviousImageState.CACHED) emptyList<String>() else listOf(oldUrl),
provider.requested
)
assertEquals(
if (previousState == PreviousImageState.ERROR) listOf(failure) else emptyList<Throwable>(),
errors
)
url.value = newUrl
}
composeTestRule.runOnIdle {
assertTrue("The replacement URL must be requested", newUrl in provider.requested)
provider.complete(newUrl, newImage)
}
composeTestRule.waitForIdle()
assertRenderedImageColor(Color.Blue)
composeTestRule.runOnIdle {
assertEquals(
if (previousState == PreviousImageState.ERROR) listOf(failure) else emptyList<Throwable>(),
errors
)
assertEquals(
if (previousState == PreviousImageState.LOADING) listOf(oldUrl) else emptyList<String>(),
provider.cancelled
)
}
}

private fun assertRenderedImageColor(expected: Color) {
val pixels = composeTestRule.onNodeWithContentDescription("Loaded image")
.assertIsDisplayed()
.captureToImage()
.toPixelMap()
assertEquals(expected, pixels[pixels.width / 2, pixels.height / 2])
}

private enum class PreviousImageState { LOADING, SUCCESS, ERROR, CACHED }

private class ControlledImageProvider : ImageProvider {
val cached = mutableMapOf<String, Bitmap>()
val requested = mutableListOf<String>()
val cancelled = mutableListOf<String>()
private val pending = mutableMapOf<String, CompletableDeferred<Bitmap>>()

override fun getCached(url: String): Bitmap? = cached[url]

override suspend fun get(url: String): Bitmap {
requested.add(url)
val result = CompletableDeferred<Bitmap>()
pending[url] = result
return try {
result.await()
} catch (e: CancellationException) {
cancelled.add(url)
throw e
}
}

fun complete(url: String, bitmap: Bitmap) {
checkNotNull(pending[url]).complete(bitmap)
}

fun fail(url: String, error: Throwable) {
checkNotNull(pending[url]).completeExceptionally(error)
}

override fun clear() {
cached.clear()
}
}

@Test
fun asyncImage_rendersWithoutCrashing() {
composeTestRule.setContent {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand All @@ -31,6 +32,7 @@ import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.adobe.marketing.mobile.concierge.ui.theme.ConciergeTheme
import com.adobe.marketing.mobile.concierge.utils.image.LocalImageProvider
import kotlinx.coroutines.CancellationException

/**
* AsyncImage composable to load and display an image from a URL asynchronously.
Expand Down Expand Up @@ -125,22 +127,29 @@ private data class ImageResult(
@Composable
private fun rememberRemoteImage(url: String, onError: ((Throwable) -> Unit)? = null): ImageResult {
val provider = LocalImageProvider.current
return produceState(
initialValue = provider.getCached(url)?.asImageBitmap()?.let { bitmap ->
ImageResult(image = bitmap, state = ImageLoadingState.Success)
} ?: ImageResult(image = null, state = ImageLoadingState.Loading),
key1 = url
) {
if (value.state == ImageLoadingState.Loading) {
try {
val bitmap = provider.get(url).asImageBitmap()
value = ImageResult(image = bitmap, state = ImageLoadingState.Success)
} catch (e: Exception) {
// Image loading failed
value = ImageResult(image = null, state = ImageLoadingState.Error)
onError?.invoke(e)
// Key the state holder on `url` so that when the URL changes (e.g. the welcome config is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] This comment says the state holder is keyed on url, but the code doesn't do that. produceState(initialValue, key1 = url) keeps its state in an unkeyed remember { mutableStateOf(initialValue) }; key1 only restarts the producer (LaunchedEffect). On a URL change, the previous value is kept and the value.state == ImageLoadingState.Loading guard below skips loading the new URL whenever the old URL had already:

The rethrows only fix the in-flight case. Suggest actually resetting the state per URL, e.g.:

return key(url) {
    produceState(...) { ... }.value
}

// swapped in after the first composition) the image reloads from a fresh Loading state instead
// of reusing a stale Success/Error state for the previous URL.
return key(url) {
produceState(
initialValue = provider.getCached(url)?.asImageBitmap()?.let { bitmap ->
ImageResult(image = bitmap, state = ImageLoadingState.Success)
} ?: ImageResult(image = null, state = ImageLoadingState.Loading),
key1 = url
) {
if (value.state == ImageLoadingState.Loading) {
try {
val bitmap = provider.get(url).asImageBitmap()
value = ImageResult(image = bitmap, state = ImageLoadingState.Success)
} catch (e: CancellationException) {
// Cancellation must not become a load error or invoke the error callback.
throw e
} catch (e: Exception) {
// Image loading failed
value = ImageResult(image = null, state = ImageLoadingState.Error)
onError?.invoke(e)
}
}
}
}.value
}.value
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.adobe.marketing.mobile.services.Log
import com.adobe.marketing.mobile.services.NetworkCallback
import com.adobe.marketing.mobile.services.NetworkRequest
import com.adobe.marketing.mobile.services.ServiceProvider
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
Expand Down Expand Up @@ -122,6 +123,9 @@ internal class DefaultImageProvider(
connection.close()

bitmap ?: throw IOException("Failed to decode image from URL: $url")
} catch (e: CancellationException) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] Inside downloadScope.async, this catch is effectively unreachable, because downloadScope is never cancelled.

The CancellationException that causes the blank images is thrown from await() in the caller and caught by rememberRemoteImage's catch (e: Exception) in AsyncImage.kt, which marks the image as Error. That's where it needs to be rethrown.

// Normal coroutine cancellation; rethrow so it is not misreported as a load error.
throw e
} catch (e: IOException) {
Log.error(
ConciergeConstants.EXTENSION_NAME,
Expand Down
Loading