領域層最簡單的說法,就是這個類別只能引用 Kotlin,所以不能在 import 看到 Android 的東西
例如
import android.content.Context
data class Note(
val id: Long = 0,
val title: String,
val content: String,
val categoryId: Long,
val tags: List<String>,
val createdAt: Long,
val updatedAt: Long
)
data class Category(
val id: Long = 0,
val name: String,
val sortOrder: Int
)
interface NoteRepository {
fun getAllNotes(): Flow<List<Note>>
fun getAllCategories(): Flow<List<Category>>
suspend fun getNoteById(id: Long): Note?
suspend fun saveNote(note: Note)
suspend fun deleteNote(note: Note)
suspend fun saveCategory(category: Category)
suspend fun deleteCategory(category: Category)
}
fun NoteEntity.toDomain(): Note {
return Note(
id = this.id,
title = this.title,
content = this.content,
categoryId = this.categoryId,
tags = this.tags,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
fun Note.toEntity(): NoteEntity {
return NoteEntity(
id = this.id,
title = this.title,
content = this.content,
categoryId = this.categoryId,
tags = this.tags,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
fun CategoryEntity.toDomain(): Category {
return Category(
id = this.id,
name = this.name,
sortOrder = this.sortOrder
)
}
fun Category.toEntity(): CategoryEntity {
return CategoryEntity(
id = this.id,
name = this.name,
sortOrder = this.sortOrder
)
}
class NoteRepositoryImpl @Inject constructor(
private val noteDao: NoteDao,
private val categoryDao: CategoryDao
) : NoteRepository {
override fun getAllNotes(): Flow<List<Note>> {
return noteDao.getAllNotes().map { entities ->
entities.map { it.toDomain() }
}
}
override fun getAllCategories(): Flow<List<Category>> {
return categoryDao.getAllCategories().map { entities ->
entities.map { it.toDomain() }
}
}
override suspend fun getNoteById(id: Long): Note? {
return noteDao.getNoteById(id)?.toDomain()
}
override suspend fun saveNote(note: Note) {
noteDao.insertNote(note.toEntity())
}
override suspend fun deleteNote(note: Note) {
noteDao.deleteNote(note.toEntity())
}
override suspend fun saveCategory(category: Category) {
categoryDao.insertCategory(category.toEntity())
}
override suspend fun deleteCategory(category: Category) {
categoryDao.deleteCategory(category.toEntity())
}
}
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindNoteRepository(
noteRepositoryImpl: NoteRepositoryImpl
): NoteRepository
}