The Clean Architecture DataSource

Clean Data Sources in Android

Michal Ankiersztajn
2 min readJul 31, 2024

What is DataSource?

To understand why you should use and what is DataSource, you first need to understand SSOT(Single Source Of Truth) because it’s the main idea behind it.

When you’re working with SSOT you’re 100% sure that the data is up-to-date and that it’s the place responsible for data altering operations.

DataSource at its core is an SSOT. It’s also the first place the data flows in the app. Meaning it’s a wrapper for databases, REST APIs, WebSockets and more.

Naming Convention

There are many naming conventions for naming the DataSources . However, the one that I find working the best is the one from Android Developers:

type of data + type of source + DataSource

It’s pretty straightforward to read. Say you need to both fetch and cache News, then you would need to create 2 datasources:

  • NewsLocalDataSource — responsible for caching the data on the device.
  • NewsRemoteDataSource — responsible for fetching the data through some API.

How to create a DataSource?

Following the naming convention, you’ll want to create an interface that defines the operations and a class implementing it. What’s crucial is that you’ll need 2 interfaces if one of the sources is local and the other is remote.

What many people get wrong is they create 1 interface and 2 implementations local + remote, whilst you might not have API endpoints that can realize locally needed operations and the other way around.

It all should get clearer with an example:

Example

We’ll take our previous News example, where we need both Local and Remote DataSources. The overall architecture will look like this:

DataSource diagram

The only thing that might differ is the Repository . However, when working with Clean Architecture it’s very unlikely.

Here, the implementation details are hidden by interface . The classes implementing these interfaces expose implementation details in their name. In that case, the Local is implemented with Room whilst Remote is implemented with Retrofit. The name convention is as follows:

library name + type of data + type of source + DataSource

However, you should never depend on the implementation detail, meaning that the repository in the above diagram cannot depend on concrete classes (RoomNewsLocalDataSource and RetrofitNewsRemoteDataSource ) and can only depend on abstraction (NewsLocalDataSource and NewsRemoteDataSource ).

Because of that you're easily able to mock your DataSources as well as swap the implementation details without changing the behavior in the future.

Thanks for reading! Please follow me if you’ve learned something new!

--

--

Michal Ankiersztajn

Android/Kotlin Developer & Applied Computer Science Engineer