Fakhrul Siddiqei
Fakhrul's Terminal


Fakhrul's Terminal

What is UseCase and why to use?

What is UseCase and why to use?

Make your code base more simple to understand and easy to work with!

Fakhrul Siddiqei's photo
Fakhrul Siddiqei
·Feb 23, 2022·

2 min read

Table of contents

  • What is Use case?
  • Why to use Use case's?
  • Example of an Use case
  • Advantages of using Use cases

What is Use case?

The purpose of the UseCases is to be a mediator between your ViewModels and Repositorys.

Let’s say in the future you decide to add an “edit post” feature. All you have to do is add a new EditPost UseCase and all its code will be completely separate and decoupled from other UseCases. We’ve all seen it many times: New features are introduced and they inadvertently break something in preexisting code. Creating a separate UseCase helps immensely in avoiding that.

Of course, you can’t eliminate that possibility 100 percent, but you sure can minimize it. This is what separates Clean Architecture from other patterns: The code is so decoupled that you can treat every layer as a black box.

Why to use Use case's?

We know about Clean Architecture. It has seperate layers and one of them is domain layer. The domain layer contains all the use cases of your application. Use case's are responsible for working with singular task. It simplifly the purpose of Single-responsiblity Principle of SOLID principle.

Example of an Use case

Below, a use case example has given. Where we getting hourly weather data from weather repository. It is handling single response and purpose.

class HourlyDataUseCase {
    var weatherRepository: WeatherRepository = WeatherRepository()
    private val job = CoroutineScope(Dispatchers.IO)

    fun invoke(weatherRequestModel: WeatherRequestModel, isSuccess:(WeatherDataHourly)->Unit, isFailed:(String)->Unit) {
        val weather = weatherRepository.getHourly(
        job.launch {
            weather.execute().apply {
                when (this.isSuccessful){
    fun cancel(onCancelled:()->Unit){
        job.cancel("Job Cancelled")

to learn more feel free to visit my clean architecture demo project https://github.com/FakhrulASA/weatherLy-Clean-Architecture

Advantages of using Use cases

  • Aids in the removal of code Duplication: Instead of placing the same procedure in two distinct ViewModels, we can now easily call one method from our USE CASE class to access User Profile data in two different ViewModels.

  • Screaming Architecture: When we can obtain the basic notion of what a new project does and is about just by glancing at it at a glance, we call it "screaming architecture." Similarly, Use Cases should be written in such a manner that anyone can figure out what they do just by glancing at the class name. GetUsersUseCase, for example, is used to retrieve a list of users from a data source.

Share this