https://kotlinlang.org logo
#compose
Title
# compose
m

Marc Reichelt

06/08/2020, 9:50 PM
Hey there! What is the latest way to load an image from the URL? I tried to set this up with Coil (I saw a blog post by @Colin White, but that’s against an old version of compose), but in the end I sort of gave up. I didn’t find any api or any docs on how to load an image from the web. Did someone get this working with the latest Compose?
z

Zach Klippenstein (he/him) [MOD]

06/08/2020, 9:53 PM
k

Klaas Kabini

06/09/2020, 7:59 AM
Here is how I accomplished it in compose.
Copy code
@Composable
fun loadImageFromUrl(url: String): ImageAsset? {
    val activity = context as ComposeActivity

    if (url.isEmpty()) {
        return null
    }

    return with(ViewModelProvider(activity).get(BitmapRequestorViewModel::class.java)) {
        val observableBitmapState = fetchBitmapFromUrl(url).observeAsState()
        observableBitmapState.value?.asImageAsset()
    }
}

internal class BitmapRequestorViewModel : ViewModel() {
    fun fetchBitmapFromUrl(url: String) = liveData {
        val picasso = Picasso.get()
        picasso.fetchBitmap(url)?.let {
            emit(it)
        }
    }
}

suspend fun Picasso.fetchBitmap(url: String): Bitmap? =
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) { load(url).get() }
👍 2
m

Marc Reichelt

06/09/2020, 8:57 AM
@Zach Klippenstein (he/him) [MOD] Nice, thanks a lot! That seems to be exactly what I need. I also like the example of you @Klaas Kabini - it looks simpler than I would have imagined, and is good to learn how to do these things yourself. Nice!