
DataSource
네트워크, 로컬 DB, 파일, 메모리 등에서 데이터를 제공한다.
데이터와 직접적인 연관이 있는 클래스이기 때문에 해당 클래스에서는 CRUD의 기능만 담당한다.
DataSource 클래스에서는 하나의 데이터 저장소만 사용해야 한다.
예를 들어, 네트워크 통신 DataSource에는 네트워크 통신과 관련 된 기능만 존재해야 한다.
class NewsRemoteDataSource(
private val newsApi: NewsApi,
private val ioDispatcher: CoroutineDispatcher
) {
/**
* Fetches the latest news from the network and returns the result.
* This executes on an IO-optimized thread pool, the function is main-safe.
*/
suspend fun fetchLatestNews(): List<ArticleHeadline> =
// Move the execution to an IO-optimized thread since the ApiService
// doesn't support coroutines and makes synchronous requests.
withContext(ioDispatcher) {
newsApi.fetchLatestNews()
}
}
// Makes news-related network synchronous requests.
interface NewsApi {
fun fetchLatestNews(): List<ArticleHeadline>
}
Repository
DataSource를 기반으로 가져온 데이터들을 목적에 따라 가공하여 사용한다.
사용하는 DataSource는 여러 개일 수도 있으며, 여러 DataSource 간의 충돌 또한 Repository에서 해결한다.
목적에 따라 가공한 데이터는 일관성을 위해 임의로 수정 또는 변경할 수 없다.
Repository는 최대한 기능에 따라 분리하여 구현하며, 필요에 따라 다른 Layer에서 여러 Repository를 가져다 사용할 수 있다.
// NewsRepository is consumed from other layers of the hierarchy.
class NewsRepository(
private val newsRemoteDataSource: NewsRemoteDataSource
) {
suspend fun fetchLatestNews(): List<ArticleHeadline> =
newsRemoteDataSource.fetchLatestNews()
}
클래스명
Repository의 클래스명은 담당하는 데이터에 따라 지정된다.
NewsRepository, MovieRepository 등과 같이 클래스명으로 어떤 데이터를 관리하고 있는지 알 수 있어야 한다.
오류 처리
공식문서에 따르면 DataLayer를 호출하는 UI Layer에서 에러를 핸들링해야 한다고 나와있습니다.
1. UI Layer에서 try-catch 문으로 예외 처리 하는 방법
2. runCatching을 사용하여 Result 객체로 처리하는 방법
https://snaildeveloper.tistory.com/116
runCatching 예외 처리
runCatching은 Kotlin에서 제공하는 예외처리 함수로 성공, 실패에 따른 결과를 Result 객체로 변환하여 반환한다.inline fun runCatching(block: () -> R): Resultinline fun T.runCatching(block: T.() -> R): Result Result 생성run
snaildeveloper.tistory.com
'안드로이드 > 디자인패턴' 카테고리의 다른 글
SOILD 원칙 (0) | 2025.03.08 |
---|---|
SingleTon (0) | 2025.03.08 |
함수형 프로그래밍 (0) | 2024.08.13 |
[Java] 객체 지향 (0) | 2024.01.24 |
[디자인 패턴] MVVM (0) | 2023.11.03 |