Ktorfit Integration¶
Sandwich offers seamless extensions of ApiResponse
for Ktorfit by utilizing Sandwich's converter factory. Basically, Ktorfit was built top of the Ktor, so you can use Ktor extensions as well.
To utilize these Ktorfit supports, simply add the following dependency:
dependencies {
implementation "com.github.skydoves:sandwich-ktorfit:$version"
}
dependencies {
implementation("com.github.skydoves:sandwich-ktorfit:$version")
}
For Kotlin Multiplatform, add the dependency below to your module's build.gradle.kts
file:
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.github.skydoves:sandwich-ktorfit:$version")
}
}
}
ApiResponseConverterFactory¶
First, build your Ktorfit
instance with the ApiResponseConverterFactory
call adapter factory:
val retrofit = Ktorfit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(ApiResponseConverterFactory.create())
.build()
Next, define your service interface with the suspend
keyword and ApiResponse<*>
as the response type:
interface MyApiService {
@GET("DisneyPosters.json")
suspend fun fetchData(): ApiResponse<List<Poster>>
}
Lastly, execute the defined service to receive the ApiResponse
:
val apiService = ktorfit.create<MyApiService>()
val response: ApiResponse<List<Poster>> = apiService.fetchData()
response.onSuccess {
// handles the success case when the API request gets a successful response.
mutableStateFlow.value = data
}.onError {
// handles error cases when the API request gets an error response.
}.onException {
// handles exceptional cases when the API request gets an exception response.
}
ApiResponse from the HttpClient¶
Basically, Ktorfit is built on top of Ktor, so you can leverage all ApiResponse
extensions as described in the Ktor documentation.