Applied Clean Architecture - How to Design Use Cases (Interactors) on Android
Please note: Although I’ve succesfully implemented this approach in one of my Applications (check out my Open Source repo PosTrainer), I’m still very much in the process of optimizing things. Feel free to give feedback, and don’t take my opinions as gospel please.
A [Use Case] can be thought of as a series of Steps toward a single a plainly stated outcome:
see use_case_one.jpg for visual aid
Examples: Plain English: Code/Classes: “Set Photo” UpdateUserDetails.java
“Delete Song” CreateAccount.java
“Get Location” DismissAlarm.kt
Although a Use Case works toward one Outcome, it may succeed or fail based on input from multiple [Service Objects] which may need to execute in a specific order, and may also be Asynchronous in nature
For example, let’s say we are writing a Use Case to “Display Local Businesses”. Assuming we have an API which can give us this data if we provide the GPS Location, we must necessarily perform more than one ‘Step’ to reach a ‘Single Outcome’:
- Acquire the GPS Data from System Services of a Device
- Make a call to our API which recieves GPS Location and returns appropriate Data
Simple Use Case flow:
Desired Outcome (n) Steps Outcomes
1. Auth Fails Display Error Message
Log User In
2. Auth Succeeds User Logged In
Knowing the Use Cases may or may not have to talk to multiple Services, in a particular order, which may (and chances are will be) Asynchronous, it helps to have a powerful Framework behind you; such as Reactive Extensions. On the Android Platform, RxJava allows you to deal with Asynchronous Sources and Handle events (result of some step) as they occur. If we make Use of RxAndroid (a Scheduler which can call back to the Main Thread in Android OS), we can also handle these operations on an appropriate thread (IO) and Call back on the Main Thread.
In use_case_two.jpg, I’ve written out a rough diagram on this process of reacting to events and coordinating system Services. This is based directly off of a Use Case I’ve written in PosTrainer, and I’ve done my best to give a rough idea of how that executes visually.
Design Example: SetAlarm.java “User Wishes to Set an Alarm”