Android/Development Tips

Coil 썸네일 구현하기

Nanamare 2021. 11. 23. 01:14
728x90

Coil 은 썸네일 기능을 따로 제공하지 않고 있습니다.

이때 사용해 볼 수 있는 확장 함수 입니다.

fun ImageView.loadOriginalImage(originUrl: String, thumbnailUrl: String) {
    CoroutineScope(Dispatchers.Main.immediate).launch {
        val thumbnail = async(Dispatchers.IO) {
            val request = ImageRequest.Builder(context)
                .data(thumbnailUrl)
                .build()
            Coil.execute(request).drawable
        }

        val original = async(Dispatchers.IO) {
            val request = ImageRequest.Builder(context)
                .data(originUrl)
                .build()
            Coil.execute(request).drawable
        }
        original.invokeOnCompletion { thumbnail.cancel() }

        val thumbDrawable = try {
            thumbnail.await()
        } catch (e: CancellationException) {
            null
        }
        setImageDrawable(thumbDrawable)

        val fullSizeDrawable = original.await()
        setImageDrawable(fullSizeDrawable)
    }
}
728x90