0
0
Android Kotlinmobile~5 mins

Clean Architecture layers in Android Kotlin

Choose your learning style9 modes available
Introduction

Clean Architecture helps organize app code into clear parts. This makes apps easier to build, test, and change.

When building an app that will grow bigger over time.
When you want to keep your app easy to test and fix bugs.
When working in a team so everyone understands the code structure.
When you want to separate app logic from UI and data storage.
When you want to reuse parts of your app in other projects.
Syntax
Android Kotlin
interface UseCase {
    fun execute()
}

class Repository {
    fun getData(): String {
        return "Data"
    }
}

class ViewModel(private val useCase: UseCase) {
    fun load() {
        useCase.execute()
    }
}

The layers communicate only in one direction.

Each layer has its own responsibility.

Examples
This is the domain layer interface. It defines app rules.
Android Kotlin
interface UseCase {
    fun execute()
}
This is the data layer. It handles data fetching and storage.
Android Kotlin
class Repository {
    fun getData(): String {
        return "Data"
    }
}
This is the presentation layer. It connects UI with app logic.
Android Kotlin
class ViewModel(private val useCase: UseCase) {
    fun load() {
        useCase.execute()
    }
}
Sample App

This simple program shows three layers: domain, data, and presentation. The ViewModel calls the UseCase, which returns a greeting string.

Android Kotlin
interface UseCase {
    fun execute(): String
}

class GetGreetingUseCase : UseCase {
    override fun execute(): String {
        return "Hello from Domain Layer!"
    }
}

class Repository {
    fun fetchData(): String {
        return "Data from Data Layer"
    }
}

class ViewModel(private val useCase: UseCase) {
    fun showGreeting(): String {
        return useCase.execute()
    }
}

fun main() {
    val useCase = GetGreetingUseCase()
    val viewModel = ViewModel(useCase)
    println(viewModel.showGreeting())
}
OutputSuccess
Important Notes

Keep dependencies pointing inward: outer layers depend on inner layers.

Domain layer should not depend on Android or any framework.

Presentation layer handles UI and user input only.

Summary

Clean Architecture divides app into layers: domain, data, and presentation.

Each layer has a clear job and talks only to the next layer inside.

This makes apps easier to maintain, test, and grow.