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?
@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!