Product catalog with network fetching and Answer type for error handling
The Product Component handles product catalog operations, fetching products from a remote API and providing them to the application. It demonstrates network integration and the Answer pattern for elegant error handling.
package com.denisbrandi.androidrealca.product.domain.modelimport com.denisbrandi.androidrealca.money.domain.model.Moneydata class Product( val id: String, val name: String, val money: Money, val imageUrl: String)
Uses Ktor client to GET products from the JSON generator API
2
Add authorization
Includes access token header for API authentication
3
Handle response
Checks HTTP status and deserializes JSON response
4
Map to domain
Converts DTOs to domain models, wrapping in Answer type
5
Handle errors
Catches network exceptions and HTTP errors, returning Answer.Error
All errors (network failures, HTTP errors) are currently mapped to Answer.Error(Unit). In production, you might want to provide more specific error types.
Data transfer object for API response deserialization.
package com.denisbrandi.androidrealca.product.data.modelimport kotlinx.serialization.*@Serializabledata class JsonProductResponseDTO( @SerialName("id") val id: Int, @SerialName("name") val name: String, @SerialName("price") val price: Double, @SerialName("currency") val currency: String, @SerialName("imageUrl") val imageUrl: String)
The DTO uses Int for the ID (as received from API), but it’s converted to String in the domain model for consistency with other components.
The product component uses the Answer type from the foundations module for type-safe error handling.
package com.denisbrandi.androidrealca.foundationssealed class Answer<out T, out E> { data class Success<out T>( val data: T, ) : Answer<T, Nothing>() data class Error<out E>( val reason: E, ) : Answer<Nothing, E>() fun <C> fold( success: (T) -> C, error: (E) -> C, ): C = when (this) { is Success -> success(data) is Error -> error(reason) }}
Why Answer over Result or exceptions?
Type-safe errors: The error type E is part of the type signature, making error handling explicitFunctional composition: The fold method enables functional programming patternsNo exceptions: Errors are values, not exceptions, leading to more predictable codeClear contracts: API consumers know exactly what errors to expect