Ktor
Ktor is a lightweight, open-source framework built specifically for Kotlin. It streamlines the development process for asynchronous web applications and APIs.
Usage
Dependencies
Within your app
module’s build.gradle.kts
file, incorporate the following dependencies:
implementation(project(":networking:ktor"))
Example
This documentation guides you through using the KtorClient
class, designed to interact seamlessly with an API. It leverages Kotlin’s coroutines and Ktor’s asynchronous features for efficient and scalable communication.
Since KtorClient
is an abstract class, you’ll need to create a concrete subclass tailored to your API’s configuration. Here’s a breakdown of the key steps:
Creating a Ktor client
class MyKtorClient: KtorClient() {
override val baseUrl: String = ""
// Optional access token retrieval function if your API requires it
// For example to get it from your DataStore Preferences or Shared Preferences
override val accessToken: (suspend () -> String)? = null
override val timeoutMillis: Long = 30000 // Adjust timeout as needed
override val isLoggingEnabled: Boolean = true // Enable or disable logging
}
- Provide the base URL of your API in the
baseUrl
property. - Provide a function for retrieving an access token (if applicable) in the
accessToken
property. - Adjust the
timeoutMillis
value to suit your needs. - Set
isLoggingEnabled
to true or false for detailed logging.
Performing a request
The doRequest
method provides a convenient way to execute requests to your API. Here’s how to use it:
val client = MyKtorClient()
suspend fun getUsers(): NetworkResponse<List<UserResponse>> {
return client.doRequest<List<UserResponse>> {
method = HttpMethod.Get
url {
appendPathSegments("users")
}
}
}
The doRequest
method handles various aspects:
- Automatically includes the access token in the Authorization header if a retrieval function is provided.
- Encodes request payloads in JSON format using the pre-configured JSON serializer.
- Decodes JSON responses from the API.
- Catches and handles exceptions for network errors and serialization issues.
It returns a NetworkResponse
sealed class, which can either be a Success
containing the parsed response data or an Error
representing different failure scenarios. You’ll need to handle the specific response type based on your API’s response format (e.g., UserResponse in this example).
Additional Considerations
- Error Handling: The provided code demonstrates basic error handling. You might want to customize it further to cater to your specific requirements, such as logging errors or retrying requests upon certain error conditions.
- Advanced Ktor Features: Ktor offers a rich ecosystem of plugins and features. If your use case requires additional functionalities like authentication beyond access tokens, custom interceptors, or webSockets, explore relevant Ktor plugins.
More information on Ktor Client can be found in the official documentation .