03 March, 2024

Download an image to local disk and show it with Compose.

 



class DownloadImageUseCase @Inject constructor(
@ApplicationContext private val context: Context,
private val dispatchersProvider: DispatchersProvider,
) {
suspend operator fun invoke(imageUrl: String): String? = withContext(dispatchersProvider.io()) {
try {
val input = URL(imageUrl).openStream()
val fileName = imageUrl.substringAfterLast("/")
val file = File(context.filesDir, fileName)
FileOutputStream(file).use { output ->
input.copyTo(output)
}
file.absolutePath
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
 
 
viewModelScope.launch {
state.update { oldState ->
oldState.copy(
imagePath =
downloadImageUseCase(
"https://apod.nasa.gov/apod/image/2403/IM_Odysseus_landing-1100x600.png",
),
)
}
}
 

@Composable
fun DisplayImageFromDisk(imagePath: String?) {
imagePath?.let {
Image(
painter = rememberAsyncImagePainter(File(it)),
contentDescription = "Cached Image",
modifier = Modifier.fillMaxWidth()
)
}
}
 

No comments:

Post a Comment