Networking with Retrofit and Coroutines

Android Development 14 min min read Updated: Nov 16, 2026 Intermediate
Networking with Retrofit and Coroutines
Intermediate Topic 1 of 6

Setup

kotlin // build.gradle.kts implementation(libs.retrofit) implementation(libs.retrofit.kotlinx.serialization.converter) implementation(libs.okhttp) implementation(libs.okhttp.logging.interceptor) implementation(libs.kotlinx.serialization.json) // AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET" />

Use the latest stable versions from each library's page. We use the free JSONPlaceholder practice API.

Model

kotlin @Serializable data class PostDto( val id: Int, val userId: Int, val title: String, val body: String )

API Interface

kotlin interface PostApi { @GET("posts") suspend fun getPosts(): List<PostDto> @GET("posts/{id}") suspend fun getPost(@Path("id") id: Int): PostDto @GET("posts") suspend fun getPostsByUser(@Query("userId") userId: Int): List<PostDto> @POST("posts") suspend fun createPost(@Body post: PostDto): PostDto }

Create Retrofit

kotlin object ApiFactory { private val json = Json { ignoreUnknownKeys = true } // do not crash on extra fields private val client = OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE }) .build() val postApi: PostApi = Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com/") .client(client) .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() .create(PostApi::class.java) }
Why the logger only in debug: HTTP logs can contain private data. Never leave BODY logging on in release builds.

Handle Errors with a Result

kotlin sealed interface Resource<out T> { data class Success<T>(val data: T) : Resource<T> data class Failure(val message: String) : Resource<Nothing> } suspend fun <T> safeApiCall(block: suspend () -> T): Resource<T> = try { Resource.Success(block()) } catch (e: CancellationException) { throw e } catch (e: HttpException) { Resource.Failure("Server error ${e.code()}") } catch (e: IOException) { Resource.Failure("No internet connection") } catch (e: Exception) { Resource.Failure(e.message ?: "Unknown error") }

Repository and ViewModel

kotlin class PostRepository(private val api: PostApi) { suspend fun posts(): Resource<List<PostDto>> = safeApiCall { api.getPosts() } } data class PostsUiState( val posts: List<PostDto> = emptyList(), val isLoading: Boolean = true, val error: String? = null ) class PostsViewModel(private val repository: PostRepository) : ViewModel() { private val _state = MutableStateFlow(PostsUiState()) val state = _state.asStateFlow() init { load() } fun load() = viewModelScope.launch { _state.update { it.copy(isLoading = true, error = null) } when (val result = repository.posts()) { is Resource.Success -> _state.update { it.copy(posts = result.data, isLoading = false) } is Resource.Failure -> _state.update { it.copy(error = result.message, isLoading = false) } } } }

Screen

kotlin @Composable fun PostsScreen(viewModel: PostsViewModel) { val state by viewModel.state.collectAsStateWithLifecycle() when { state.isLoading -> Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator() } state.error != null -> Column(Modifier.fillMaxSize(), Arrangement.Center, Alignment.CenterHorizontally) { Text(state.error!!) Button(onClick = viewModel::load) { Text("Retry") } } else -> LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { items(state.posts, key = { it.id }) { post -> Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Text(post.title, style = MaterialTheme.typography.titleMedium) Text(post.body, maxLines = 2, overflow = TextOverflow.Ellipsis) } } } } } }
Security: Use HTTPS. Never ship secret API keys inside the app, because they can be extracted. Use your own backend for secrets.

Conclusion

Retrofit turns an interface into API calls. Combine it with coroutines, a Resource wrapper, a repository and a ViewModel.

Quick Summary: Add INTERNET permission, define an API interface with suspend functions, build Retrofit with a converter and catch errors in a repository.

Get Newsletter

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