Skip to content

Define a abstraction layer to use DAO

Devrath edited this page Oct 22, 2023 · 3 revisions

Main steps in using the abstraction on top of DAO

Step-1

  • Define an interface class that has methods that return the data in each abstract method of DAO.
interface AppRepository {
    suspend fun addBook(book: Book)
    fun getBooks(): Flow<List<BookAndGenre>>
    fun getAllReviews(): Flow<List<ReviewAndBook>>
    suspend fun removeBook(book:Book)
    . . . . . . . . . . . . . . . . . . . . 
    . . . . . other methods . . . . . . . . 
    . . . . . . . . . . . . . . . . . . . . 
}

Step-2

  • Implement this method in a class and override the methods of the interface`.
  • In the constructor of the class have the parameters of the DAO's.
  • Since we have used hilt, We need to have a module object that provides the DAO instance reference. With this, we can pass the DAO references in the constructor of the implementation of the repository.
  • Since we have annotated the constructor of the repository implementation with @Inject, Now we can directly use this class reference as constructor injection.

Step-3

  • Constructor injection is used for injecting the repository
class AddBookUseCase @Inject constructor(
    @IoDispatcher val dispatcher: CoroutineDispatcher,
    private val appRepositoryImpl: AppRepositoryImpl,
) : SuspendUseCase<AddBookAllInputs, Result<Boolean>>(dispatcher) {
    override suspend fun execute(parameters: AddBookAllInputs): Result<Boolean> =
        suspendCancellableCoroutine { coroutine ->
            
        }
}

Why the need of abstraction πŸ˜„

  • We could have directly injected DAO but we have added one more layer of abstraction because its very powerful to combine the results from 2 or more DAO's if needed.