Images with Coil and Loading, Empty and Error States

Android Development 10 min min read Updated: Nov 16, 2026 Intermediate
Images with Coil and Loading, Empty and Error States
Intermediate Topic 3 of 6

Setup

kotlin implementation(libs.coil.compose) implementation(libs.coil.network.okhttp) // for Coil 3, network support is a separate artifact

AsyncImage

kotlin AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data("https://picsum.photos/300") .crossfade(true) .build(), contentDescription = "Random photo", placeholder = painterResource(R.drawable.placeholder), error = painterResource(R.drawable.broken_image), contentScale = ContentScale.Crop, modifier = Modifier.size(150.dp).clip(RoundedCornerShape(16.dp)) )
Caching: Coil caches images in memory and on disk by default, so repeated images load instantly and use less data.

Show a Spinner While Loading

kotlin SubcomposeAsyncImage( model = url, contentDescription = title, loading = { CircularProgressIndicator(Modifier.size(24.dp)) }, error = { Icon(Icons.Default.BrokenImage, contentDescription = null) }, modifier = Modifier.size(100.dp) )

A Generic UI State

kotlin sealed interface UiState<out T> { data object Loading : UiState<Nothing> data class Success<T>(val data: T) : UiState<T> data class Error(val message: String) : UiState<Nothing> } @Composable fun <T> StateContent( state: UiState<T>, onRetry: () -> Unit, isEmpty: (T) -> Boolean = { (it as? Collection<*>)?.isEmpty() == true }, content: @Composable (T) -> Unit ) { when (state) { UiState.Loading -> Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator() } is UiState.Error -> Column( Modifier.fillMaxSize().padding(24.dp), Arrangement.Center, Alignment.CenterHorizontally ) { Icon(Icons.Default.CloudOff, contentDescription = null, Modifier.size(64.dp)) Spacer(Modifier.height(8.dp)) Text(state.message, textAlign = TextAlign.Center) Spacer(Modifier.height(16.dp)) Button(onClick = onRetry) { Text("Try again") } } is UiState.Success -> if (isEmpty(state.data)) { Box(Modifier.fillMaxSize(), Alignment.Center) { Text("Nothing here yet") } } else { content(state.data) } } }

Pull to Refresh

kotlin @OptIn(ExperimentalMaterial3Api::class) @Composable fun RefreshableList(items: List<String>, isRefreshing: Boolean, onRefresh: () -> Unit) { PullToRefreshBox(isRefreshing = isRefreshing, onRefresh = onRefresh) { LazyColumn(Modifier.fillMaxSize()) { items(items) { Text(it, Modifier.padding(16.dp)) } } } }
Remember: Always design four screens for network data: loading, content, empty and error. Beginners often build only the content.

Conclusion

Coil loads and caches images with one composable. A sealed UiState ensures you never forget loading, empty and error screens.

Quick Summary: Use AsyncImage with placeholder and error, model screen state with a sealed interface and add PullToRefreshBox.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators