androidimagekotlinandroid-jetpack-composecoil

android compose onclick asyncimage one URL returns random picture when URL is again called


Like in title said I need to update picture when got same URL, this URL whenever is called returns random picture.

Got code that is working when URL is diferent:

var model by remember { mutableStateOf(URL) }
AsyncImage(
    model = model,
    contentDescription = "",
    modifier = Modifier.clickable(onClick = {
        model = newUrl
    })
)

But I what I need is to call same URL that returns random picture:

var model by remember { mutableStateOf(URL) }
AsyncImage(
    model = model,
    contentDescription = "",
    modifier = Modifier.clickable(onClick = {
        model = URL //this is what I need
    })
)

You can check this example:

URL = https://cataas.com/cat you will see random cat every time you refresh page.


Solution

  • If you need to reload the image with the same url, you can do something like this in Coil:

    var requestId by remember { mutableStateOf(0) }
    val imageRequest = ImageRequest.Builder(LocalContext.current)
        .data(data)
        .memoryCachePolicy(CachePolicy.DISABLED)
        .diskCachePolicy(CachePolicy.DISABLED)
        .setParameter("requestId", requestId, memoryCacheKey = null)
        .build()
    
    AsyncImage(
        model = imageRequest,
        contentDescription = "",
        modifier = Modifier.clickable(onClick = {
            requestId++
        })
    )
    

    The idea for setParameter comes from this issue: https://github.com/coil-kt/coil/issues/884. Changing the parameter makes coil execute the request again. You also have to disable cache, cause unlike in the issue, request was completed successfully in this case.