0Pricing
Kotlin Multiplatform Academy · Lección

Envuelva la API tras el repositorio

Oculte Ktor y la serialización a quienes realizan las llamadas

Envuelva la API tras el repositorio es una lección gratuita de Kotlin Multiplatform Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Kotlin Multiplatform Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Now Build the Real Thing

With the interface set, you write a concrete implementation that actually fetches data behind the scenes.

Implement the Interface

Create a class that uses implements the repository interface, promising to fulfill every method it declares.

class UserRepositoryImpl : UserRepository

Inject the Ktor Client

Pass the HttpClient into the constructor instead of creating it inside, so it can be shared and replaced in tests.

class UserRepositoryImpl(private val client: HttpClient) : UserRepository

Hide the Network Call

Inside each method, make the Ktor request and return the result. Callers see clean data, never the request itself.

override suspend fun getUsers() = client.get(url).body<List<User>>()

Keep URLs Inside

Store base URLs and paths within the implementation. The rest of the app stays blissfully unaware of any endpoint.

One Place to Change

If the API path changes, you edit only this class. The interface and every caller stay untouched.

Serialization Stays Hidden

The body call turns JSON into models here, so serialization never leaks out to the UI layer.

val user: User = client.get(url).body()

Same Code, Both Apps

This implementation lives in commonMain, so the same fetching code powers Android and iOS identically.

Swap Without Breaking Callers

Because it satisfies the interface, you can replace it with a caching version later and no caller changes.

Wire It With DI

A dependency injection setup hands callers this implementation through the interface type, keeping things loosely coupled.

single<UserRepository> { UserRepositoryImpl(get()) }

The Full Wrapper

Here is the complete wrapper: it takes a client, hides the request, and returns plain domain models.

class UserRepositoryImpl(
    private val client: HttpClient
) : UserRepository {
    override suspend fun getUsers() =
        client.get("/users").body<List<User>>()
}

Quick Check

What is the main job of the repository implementation?

Recap

The implementation takes an HttpClient, performs the request, and returns domain models, keeping all networking sealed off from callers.

Preguntas frecuentes

¿La lección «Envuelva la API tras el repositorio» es gratis?

Sí — el texto completo de «Envuelva la API tras el repositorio» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Kotlin Multiplatform Academy, actualiza a CoddyKit PRO. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Envuelva la API tras el repositorio»?

Oculte Ktor y la serialización a quienes realizan las llamadas Practicas Kotlin Multiplatform Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Kotlin Multiplatform Academy?

No se requiere experiencia previa. Kotlin Multiplatform Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Envuelva la API tras el repositorio»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Kotlin Multiplatform Academy?

Sí. Cada lección de Kotlin Multiplatform Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Defina una interfaz de repositorio
  2. Envuelva la API tras el repositorio
  3. Mapee DTO a modelos de dominio
  4. Exponga resultados como Flow
← Volver a Kotlin Multiplatform Academy