简体   繁体   中英

How to to check if Coil ImageRequest is complete before returning the bitmap value

I'm trying to return the bitmap value from a lambda function but I get the error: lateinit property bitmap has not been initialized ... Is there a way to check if the ImageRequest is complete before returning the bitmap?

fun getBitmap(context:Context,imageUrl: String) : Bitmap{

    lateinit var bitmap: Bitmap
    val imageRequest = ImageRequest.Builder(context)
        .data(imageUrl)
        .target { drawable ->
           bitmap  = drawable.toBitmap() // This is the bitmap 🚨
        }
        .build()
    ImageLoader(context).enqueue(imageRequest)

    return bitmap
}

Hm... I don't have much time to explain. Just see the code and understand.

You have to use execute() instead of enqueue() . See

 private suspend fun getBitmap(context: Context, url: String): Bitmap? {
        var bitmap: Bitmap? = null
        val request = ImageRequest.Builder(context)
            .data(url)
            .target(
                onStart = {
                    Log.d(TAG, "Coil loader started.")
                },
                onSuccess = { result ->
                    Log.e(TAG, "Coil loader success.")
                    bitmap = result.toBitmapOrNull() // Or (result as BitmapDrawable).bitmap
                },
                onError = {
                    Log.e(TAG, "Coil loading error")
                }
            )
            .build()
        context.imageLoader.execute(request)

        return bitmap
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM